方法一:枚举
#include"stdio.h" //枚举
main()
{
char left[3][7],right[3][7],balan[5];
int n,i,j,k,w,state[3];
char result[2][6]={"heavy","light"};
scanf("%d",&n);
while(n--)
{
for(i=0;i<3;i++)
{
scanf("%s%s%s",left[i],right[i],balan);
if(balan[0]=='d')state[i]=-1; // state代表u、d、e三种状态
else state[i]=(balan[0]=='u');
}
for(i=0;i<12;i++)
for(w=-1;w<=1;w+=2)// w代表假设某硬币偏重或偏轻
{
for(j=0;j<3;j++)
{
int cntL=0,cntR=0;
for(k=0;left[j][k];k++) // '\0'ASCII码值为0,这样省去了计算字符串长度的过程
{
if(left[j][k]-'A'==i)cntL=w;
if(right[j][k]-'A'==i)cntR=w;
}
if(cntR-cntL!=state[j])break; //与假设不符
}
if(j!=3)continue;
printf("%c is the counterfeit coin and it is %s.\n",i+'A',result[(w+1)/2]);
}
}
return 0;
}
另一种是我参照discuss上的,设real[12],若为EVEN 则对应real值为1;否则为0;再设count[12],初值为0;若在某次称量中轻了则对应count--,重了则对应count++,最后的假币就是对应count绝对值最大的,正负号代表light或heavy
真的是集思广益,代码如下
#include"stdio.h"
#include"string.h"
#include"math.h"
main()
{
int i,n,j,tag;
char L[7],R[7],balan[5],tmp[7],result[2][6]={"heavy","light"};
scanf("%d",&n);
while(n--)
{
int real[12]={0},count[12]={0};
for(i=0;i<3;i++)
{
scanf("%s%s%s",L,R,balan);
if(balan[0]=='e')
{
for(j=0;L[j];j++){real[L[j]-'A']=1;real[R[j]-'A']=1;}
}
else
{
if(balan[0]=='u'){strcpy(tmp,L);strcpy(L,R);strcpy(R,tmp);}
for(j=0;L[j];j++){count[L[j]-'A']--;count[R[j]-'A']++;}
}
}
for(tag=0,i=0;i<12;i++)
{
if(real[i]==1)count[i]=0;
else if(abs(count[i])>abs(count[tag]))tag=i;
}
printf("%c is the counterfeit coin and it is %s.\n",tag+'A',result[count[tag]<0]);
}
return 0;
}