有12枚硬币,11真,1假,但不知假的是轻的还是重的,用一架天平称三次,告诉你结果,请你找出假币并确定是轻的还是重的。
一、输入&&输出
1.输入
注意:天平两边硬币数目是相同的
1
ABCD EFGH even
ABCI EFJK up
ABIJ EFGH even//表示的是右边的情况
2.输出
K is the counterfeit coin and it is light.
二、解决问题
1.分析
对每一枚硬币,假设它是轻的,看是否符合称量结果,若符合则解决,反之,假设它是重的,看是否符合,枚举法。
2.代码
#include <stdio.h>
#include <string.h>
int isfake(char c,int light);
char left[3][7];//天平左边硬币
char right[3][7];//天平右边硬币
char result[3][7];//结果,天平右侧的状态
void main()
{
int t;
printf("请输入要测试数据的组数t:\n");
scanf("%d",&t);
while(t--)
{
for(int i=0;i<3;i++)
scanf("%s %s %s",left[i],right[i],result[i]);
for(char c='A';c<='L';c++)
{
if(isfake(c,1))//假设c为轻的假币
{
printf("%c is the counterfeit coin and it is light.\n",c);
break;
}
else if(isfake(c,0))
{
printf("%c is the counterfeit coin and it is heavy.\n",c);
break;
}
}
}
}
int isfake(char c,int light)//假设c是假币,c是轻的
{
for(int i=0;i<3;i++)
{
char *pleft,*pright;//指向天平两边的字符串
if(light)
{
pleft=left[i];
pright=right[i];
}
else
{
//若假币是重的,左右对换
pleft=right[i];
pright=left[i];
}
switch(result[i][0])
{
//天平右边的情况
case 'u':
if(strchr(pright,c)==NULL)
return 0;
break;
case'e':
if(strchr(pleft,c)||strchr(pright,c))
return 0;
break;
case 'd':
if(strchr(pleft,c)==NULL)
return 0;
break;
}
}
return 1;
}
3.C语言strchr函数
函数原型
char *strchr(const char *str, int c)
参数
-
str-- 要被检索的 C 字符串。
-
c-- 在 str 中要搜索的字符。
功能
在参数str所指向的字符串中搜索第一次出现字符c(一个无符号字符)的位置。
返回值
返回一个指向该字符串中第一次出现的字符的指针,如果字符串中不包含该字符则返回NULL空指针。
头文件
#include <string.h>