#include
typedef struct GOODTHINGS
{
int trueIndex; //做好事的号码 -1 代表没有指示谁做了好事
int falseIndex; //没做好事的号码 -1代表没有指示谁没做好事
GOODTHINGS()
{
trueIndex = -1;
falseIndex = -1;
}
} GoodThings, *pGoodThings;
bool isOK(const pGoodThings pA, int nSizeofA);
void main()
{
GoodThings a[4];
GoodThings temp;
a[0].falseIndex = 0; //A指示自己没做好事
a[1].trueIndex = 2; //B说是C
a[2].trueIndex = 3; //C说是D
a[3].falseIndex = 3; //D说C说谎,即D指示自己没做好事
int trueCount = 0;
for(int i = 0; i < 4; i++)
{
temp.falseIndex = a[i].falseIndex;
temp.trueIndex = a[i].trueIndex;
if(i == 0 || i == 3)
{
a[i].trueIndex = i; //a[i] tell lies
a[i].falseIndex = -1;
}
else
{
a[i].falseIndex = a[i].trueIndex;
a[i].trueIndex = -1; //a[i] tell lies
}
if(isOK(a, 4) == true)
return;
a[i].falseIndex = temp.falseIndex;
a[i].trueIndex = temp.trueIndex;
}
}
bool isOK(const pGoodThings pA, int nSizeofA)
{
int trueIndex = -1; //没有指示
for(int i = 0; i < nSizeofA; i++)
{
if(pA[i].trueIndex != -1 && trueIndex == -1) //首次指示pA中谁做了好事
trueIndex = pA[i].trueIndex;
if(pA[i].trueIndex != -1 && pA[i].trueIndex != trueIndex) //与公共指示谁做好事不同,则互斥退出
return false;
}
if(trueIndex == -1)
{
printf("Can't specify the index...\r\n");
return true;
}
for(i = 0; i < nSizeofA; i++)
{
if(pA[i].falseIndex == trueIndex && pA[i].falseIndex != -1) //指示trueIndex没做好事,又指示trueIndex做了好事,互斥退出
return false;
}
printf("result index: %d\r\n", trueIndex);
return true;
}
就是假设四种情况,然后挨个去试,看哪种情况符合,这个程序的结果是2。也就是说C做了好事。
void main()
{
bool a[4]; //依次代表abcd
int trueCount = 0,i=0;
for(i=0;i<4;i++)
{
trueCount = 0;
for(int j=0;j<4;j++)
if(i==j)
a[j]=true;
else
a[j]=false;
if(a[0]==false)
trueCount++;
if(a[2]==true)
trueCount++;
if(a[3]==true)
trueCount++;
if(a[3]==false)
trueCount++;
if(trueCount==3)
break;
}
printf("%d",i);
}