算法篇【枚举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 }

 

运行:

 

转载于:https://www.cnblogs.com/littleMa/p/8519966.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值