码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 1046 Color Me Less 最详细的解题报告

时间:2014-09-30 02:39:52      阅读:339      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   ar   java   for   sp   

题目来源:POJ 1046 Color Me Less

题目大意:每一个颜色由R、G、B三部分组成,D=Math.sqrt(Math.pow((left.red - right.red), 2)+ Math.pow((left.green - right.green), 2)+ Math.pow((left.blue - right.blue), 2)) 表示两个不同颜色的之间的距离(以left和right为例,left和right分别为两种不同的颜色),现给出16组目标颜色,剩下的为待匹配的颜色,求出剩下的颜色与目标颜色中哪个最匹配,即D最小。

 

解题思路:直接枚举法,简单直接!

具体算法(java版,可以直接AC)

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4 
 5     static double distance(Color left, Color right) {
 6         return Math.sqrt(Math.pow((left.red - right.red), 2)
 7                 + Math.pow((left.green - right.green), 2)
 8                 + Math.pow((left.blue - right.blue), 2));
 9     }
10 
11     static Color getColor(Scanner input) {
12         return new Color(input.nextInt(), input.nextInt(), input.nextInt());
13     }
14 
15     public static void main(String[] args) {
16         Scanner input = new Scanner(System.in);
17         int targetCount = 16;
18         Color[] targets = new Color[targetCount];
19         for (int i = 0; i < targetCount; i++) {
20             targets[i] = getColor(input);
21         }
22         while (true) {
23             Color object = getColor(input);
24             if (object.isEnd()) {
25                 return;
26             }
27             double min = Double.MAX_VALUE;
28             int minIndex = 0;
29             for (int i = 0; i < targetCount; i++) {
30                 double dist = distance(targets[i], object);
31                 if (dist < min) {
32                     min = dist;
33                     minIndex = i;
34                 }
35             }
36             System.out.println(String.format("%s maps to %s", object.toString(),
37                     targets[minIndex].toString()));
38         }
39     }
40 }
41 
42 class Color {
43     public int red;
44     public int green;
45     public int blue;
46 
47     public Color(int red, int green, int blue) {
48         this.red = red;
49         this.green = green;
50         this.blue = blue;
51     }
52 
53     public boolean isEnd() {
54         return this.red == -1 && this.green == -1 && this.blue == -1;
55     }
56 
57     public String toString() {
58         return String.format("(%d,%d,%d)", this.red, this.green, this.blue);
59     }
60 }

 

POJ 1046 Color Me Less 最详细的解题报告

标签:style   blog   http   color   os   ar   java   for   sp   

原文地址:http://www.cnblogs.com/pinxiong/p/4001236.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!