编程语言
首页 > 编程语言> > Java-POJ1013-Counterfeit Dollar

Java-POJ1013-Counterfeit Dollar

作者:互联网

在13枚硬币中找出fake的那一个

输入:三次天平称量结果

 1 package poj.ProblemSet;
 2 
 3 import java.util.Scanner;
 4 
 5 /*
 6 我怎么觉得是贪心算法呢?
 7 起初对所有硬币标记0;
 8 如果是even,则两边所有的硬币记为真(记233);
 9 否则就对不确定的硬币记录怀疑(++或者--根据天平倾斜方向);
10 最后只要看哪个硬币的绝对值最大,也就是被怀疑的次数最多,即是假币。
11  */
12 public class poj1013 {
13     public static int[] value = new int[20];
14     public static String[] a = new String[5];
15     public static String[] b = new String[5];
16     public static String[] c = new String[5];
17     public static final int REAL = 233;
18 
19     public static void work(int r, int len, int type) {
20         if (type == 1) {
21             for (int i = 0; i < len; i++) {
22                 if (value[a[r].charAt(i)-'A'+1] != REAL) value[a[r].charAt(i)-'A'+1]++;
23                 if (value[b[r].charAt(i)-'A'+1] != REAL) value[b[r].charAt(i)-'A'+1]--;
24             }
25         }
26         else if (type == 2) {
27             for (int i = 0; i < len; i++) {
28                 if (value[a[r].charAt(i)-'A'+1] != REAL) value[a[r].charAt(i)-'A'+1]--;
29                 if (value[b[r].charAt(i)-'A'+1] != REAL) value[b[r].charAt(i)-'A'+1]++;
30             }
31         }
32         else /*if (type == 3)*/ {
33             for (int i = 0; i < len; i++) {
34                 value[a[r].charAt(i)-'A'+1] = REAL;
35                 value[b[r].charAt(i)-'A'+1] = REAL;
36             }
37         }
38 
39     }
40 
41     public static void main(String[] args) {
42         Scanner cin = new Scanner(System.in);
43         for (int n = cin.nextInt(); n-- > 0; ) {
44             for (int i = 1; i < 20; i++) value[i] = 0;
45             for (int r = 1; r <= 3; r++) {
46                 a[r] = cin.next();b[r] = cin.next();c[r] = cin.next();int len = a[r].length();
47                 if (c[r].equals("up")) work(r, len, 1);
48                 else if (c[r].equals("down")) work(r, len, 2);
49                 else /*if (c[r].equals("even"))*/ work(r, len, 3);
50             }
51             int max = 0,id = 0;
52             for (int i = 1; i <= 13; i++) {
53                 int val = Math.abs(value[i]);
54                 if (value[i] != REAL && val > max) { max = val;id = i; }
55             }
56             System.out.println((char)(id-1+'A') + " is the counterfeit coin and it is " + (value[id]>0?"heavy":"light") + ".");
57         }
58     }
59 }

 

标签:Java,charAt,int,POJ1013,Dollar,value,static,public,String
来源: https://www.cnblogs.com/JasonCow/p/12245192.html