每人兩句話,一真一假。窮舉 5! = 120 種排列,驗證邏輯條件。
#include <stdio.h>
int main(void) {
for (int a=1; a<=5; ++a)
for (int b=1; b<=5; ++b)
for (int c=1; c<=5; ++c)
for (int d=1; d<=5; ++d)
for (int e=1; e<=5; ++e) {
if (a==b||a==c||a==d||a==e||b==c||b==d||b==e||c==d||c==e||d==e) continue;
int A_true = (b==1) + (a==3);
int B_true = (b==2) + (e==4);
int C_true = (c==1) + (d==2);
int D_true = (c==5) + (d==3);
int E_true = (e==4) + (a==1);
if (A_true==1 && B_true==1 && C_true==1 && D_true==1 && E_true==1) {
printf("A:%d B:%d C:%d D:%d E:%d\n", a,b,c,d,e);
}
}
return 0;
}
輸出:A:3 B:2 C:1 D:5 E:4
三真一假。窮舉 4 種可能兇手。
int main(void) {
for (char killer='a'; killer<='d'; ++killer) {
int true_cnt = (killer!='a') + (killer=='c') + (killer=='d') + (killer!='d');
if (true_cnt == 3) printf("兇手是 %c\n", killer);
}
return 0;
}
輸出:兇手是 c
true+true=2、true+false=1 計數真值個數。a!=b... 去重,減少無效迭代。這類「邏輯推理 + 窮舉驗證」模式廣泛適用於數獨、邏輯網格、約束滿足問題。