bool state[5]
void SetAllExcept(int iexcept, bool v) {
for (int i = 0 i < 5 i++) {
if (i == iexcept) { continue }
state[i] = v
}
}
int SumWhiteExcept(int iexcept) {
int num = 0
for (int i = 0 i < 5 i++) {
if (i == iexcept) { continue }
if (state[i]) { num++ }
}
return num
}
bool CheckATrue()
{ return SumWhiteExcept(0) == 3 }
bool CheckBTrue()
{ return SumWhiteExcept(1) == 0 }
bool CheckCTrue()
{ return SumWhiteExcept(2) == 1 }
bool CheckDTrue()
{ return SumWhiteExcept(3) == 4 }
bool CheckState() {
if (state[0] != CheckATrue())
{ return false }
if (state[1] != CheckBTrue())
{ return false }
if (state[2] != CheckCTrue())
{ return false }
if (state[3] != CheckDTrue())
{ return false }
return true
}
void output(const char* msg) {
printf("Assuming %s true is right!\n", msg)
for (int i = 0 i < 5 i++) {
printf("%s", state[i] ? "white" : "black")
if (i < 4) { printf(" ") }
}
}
void AssumeATrue() {
state[0] = true
for (int i = 1 i < 5 i++) {
SetAllExcept(0, true)
state[i] = false
if (CheckState())
{ output("A") }
}
}
void AssumeBTrue() {
state[1] = true
SetAllExcept(1, false)
if (CheckState())
{ output("B") }
}
void AssumeCTrue() {
state[2] = true
for (int i = 0 i < 5 i++) {
if (i == 2) { continue }
SetAllExcept(2, false)
state[i] = true
if (CheckState())
{ output("C") }
}
}
void AssumeDTrue() {
state[3] = true
SetAllExcept(3, true)
if (CheckState())
{ output("D") }
}
void test_main() {
AssumeATrue()
AssumeBTrue()
AssumeCTrue()
AssumeDTrue()
}
基本思路是假设其中某一个人说的是真的,然后对它描述的情况对每个人进行验证,如果验证通过,那假设这个人为真就成立,并打印出结果,否则继续重新假设下一个人为真直到结束。
结果:
Assuming C true is right!
black black white black white
比如对A: A说:“我看见有三个人的是白纸,一人是黑纸”。3个人白纸一个黑纸则b+c+d+e应该为3
如果A头上是白纸即a=1 则a&&b+c+d+e==3为真 若是黑纸a=0即!a则
!a&&b+c+d+e!=3为真 不管是白还是黑(a&&b+c+d+e==3||!a&&b+c+d+e!=3)应该为真 每个人对应的都是真值就输出此时各个人头上的纸是黑还是白
运行结果为a b c d e依次为0 0 1 0 1 你检测一下
((a&&b+c+d+e==3||!a&&b+c+d+e!=3)
&&(b&&a+c+d+e==0||!b&&a+c+d+e!=0)
&&(c&&a+b+d+e==1||!c&&a+b+d+e!=1)
&&(d&&a+b+c+e==4||!d&&a+b+c+e!=4))应该为1的 其他情况下都是0
#include <stdio.h>#include <stdlib.h>
int main(int argc, char *argv[])//可以写成int main(),没问题,个人习惯
{
int a,b,c,d,e
for(a=0a<=1++a)//资深的程序员跟倾向于写成for(a=0a!=2a++)因为对电脑来说判断!=比<=更简单.
for(b=0b<=1++b)
for(c=0c<=1++c)
for(d=0d<=1++d)
for(e=0e<=1++e)
if((a&&b+c+d+e==3||!a&&b+c+d+e!=3)
&&(b&&a+c+d+e==0||!b&&a+c+d+e!=0)
&&(c&&a+b+d+e==1||!c&&a+b+d+e!=1)
&&(d&&a+b+c+e==4||!d&&a+b+c+e!=4))
{
printf("A 贴的是%s纸.\n",a?"白":"黑")
printf("B 贴的是%s纸.\n",b?"白":"黑")
printf("C 贴的是%s纸.\n",c?"白":"黑")
printf("D 贴的是%s纸.\n",d?"白":"黑")
printf("E 贴的是%s纸.\n",e?"白":"黑")
}
system("PAUSE")
return 0
}