算法篇【枚举3 -- 称量硬币】
1、问题:有12枚硬币,11枚真的和一枚假的,现在通过三次称量结果,可以判断出假币,写出算法实现判断。
输入:
ABCD EFGH even
ABCI EFJK up
ABJK EFGH down
输出:
K is the countterfeit coin and it is light。
思路:
对每一枚硬币,先假设它是轻的,看是否符合全部三次称量结果;
否则,假设它是重的,看是否符合全部三次称量结果;
如果上述两次假设都不称量,则排除该枚硬币是假币,对下一枚硬币进行同样的假设,看是否满足;
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 char Left[3][7] ; 5 char Right[3][7] ; 6 char result[3][7] ; 7 bool IsFake(char c, bool light) ; 8 //light 为真表示假设硬币为轻,否则表示假设硬币为重. 9 10 int main() 11 { 12 13 for(int i=0; i<3; i++){ 14 cout << "Please Input the string such as 'ABCD' 'EFGH' 'even' " << endl ; 15 cin >> Left[i] >> Right[i] >> result[i]; 16 cout << endl ; 17 } 18 for(char c='A'; c<='L'; c++){ 19 if( IsFake(c,true) ){ 20 cout << c << "is the counterfeit coin and it is light. \n" << endl; 21 break ; 22 } 23 else if( IsFake(c,false) ){ 24 cout << c << "is the counterfeit coin and it is heavey. \n" << endl; 25 break ; 26 } 27 } 28 return 0; 29 system("pause"); 30 } 31 32 bool IsFake(char c,bool light){ 33 for(int i=0; i<3; i++){ 34 char *pLeft, *pRight ; 35 if(light){ 36 pLeft = Left[i] ; 37 pRight = Right[i] ; 38 } 39 else{ 40 pLeft = Right[i] ; 41 pRight = Left[i] ; 42 } 43 switch(result[i][0]){ 44 case 'u': 45 if(strchr(pRight,c) == NULL) 46 return false ; 47 break ; 48 case 'e': 49 if(strchr(pLeft,c) || strchr(pRight,c)) 50 return false ; 51 break ; 52 case 'd': 53 if(strchr(pLeft,c) == NULL) 54 return false ; 55 break ; 56 } 57 } 58 return true ;//3次结果检查的循环体中,都没有return false,那么就应该是找到了满足条件的硬币,所以在循环外面return true 59 }
运行:
本文来自博客园,作者:hematologist,转载请注明原文链接:https://www.cnblogs.com/littleMa/p/8519966.html
posted on 2018-03-06 23:20 hematologist 阅读(705) 评论(0) 编辑 收藏 举报