有12枚硬币。其中有11枚真币和1枚假币。假币和真 币重量不同,但不知道假币比真币轻还是重。现在, 用一架天平称了这些币三次,告诉你称的结果,请你 找出假币并且确定假币是轻是重(数据保证一定能找 出来)。
输入
每组数据有三行,每行表示一次称量的结果。银币标号 为A-L。每次称量的结果用三个以空格隔开的字符串表示: 天平左边放置的硬币 天平右边放置的硬币 平衡状态。其 中平衡状态用``up'', ``down'', 或 ``even''表示, 分 别为右端高、右端低和平衡。天平左右的硬币数总是相等 的。
输出
输出哪一个标号的银币是假币,并说明它比真币轻还是重。
输入样例
1
ABCD EFGH even
ABCI EFJK up
ABIJ EFGH even
输出样例
K is the counterfeit coin and it is light.
解题思路:
对于每一枚硬币先假设它是轻的,看这样是否符合 称量结果。如果符合,问题即解决。如果不符合,就 假设它是重的,看是否符合称量结果。把所有硬币都 试一遍,一定能找到特殊硬币
原题为POJ上的1013题,链接为:http://poj.org/problem?id=1013
代码如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
int N=cin.nextInt();
while(N-->0){
plate[][] p = new plate[4][4];
for(int i=1;i<=3;i++)
for(int j=1;j<=3;j++)
p[i][j]=new plate(cin.next());
char t='A';
while(t<='L'){
int count=0;
for(int i=1;i<=3;i++)
if(judge(p[i][1],p[i][2],t,true).equals(p[i][3].get_s()))
count++;
if(count==3){
System.out.println(t+" is the counterfeit coin and it is heavy.");
break;
}
count=0;
for(int i=1;i<=3;i++)
if(judge(p[i][1],p[i][2],t,false).equals(p[i][3].get_s()))
count++;
if(count==3){
System.out.println(t+" is the counterfeit coin and it is light.");
break;
}
t++;
}
}
cin.close();
}
public static String judge(plate a,plate b,char c,boolean heavy){
if(!a.contain(c) && !b.contain(c))
return "even";
else{
if(heavy){
if(a.contain(c))
return "up";
else
return "down";
}
else{
if(a.contain(c))
return "down";
else
return "up";
}
}
}
}
class plate{
private String s;
boolean contain(char a){
if(s.contains(String.valueOf(a)))
return true;
else
return false;
}
boolean equal(String t){
if(s.equals(t))
return true;
else
return false;
}
plate(String t){
s=t;
}
String get_s(){
return s;
}
}