scene:
A homicide occurred in a certain place. The police identified four suspects through investigation, and one of them must be the murderer.
A said: not me
B said: yes C
C said: Yes D
D said: C is talking nonsense
It is known that one person tells a lie and three tell the truth? Who is the murderer?
analyze:
When we reason about this question, we will assume that A, B, C, and D are the murderers one by one, and then judge that they meet the condition of "one person lies, three truths".
Assumption A | Assumption B | Assumption C | Assumption D | |
A | × | √ | √ | √ |
B | × | × | √ | × |
C | × | × | × | √ |
D | √ | √ | √ | × |
According to the analysis of the table above, it can be seen that C is the murderer.
Code:
int main()
{
char killer = 0;
for (killer = 'A'; killer <= 'D'; killer++)
{
if ((killer != 'A') + (killer == 'C') + (killer == 'D') + (killer != 'D') == 3)
{
printf("%c\n", killer);
}
}
return 0;
}
Summarize:
Consider the above checkmark and wrong sign as 1 and 0. So directly judge the three checkmarks, 1+1+1+0 = 3. The simulation result is the same as the reasoning result.
scene:
Five athletes participate in the 10-meter platform diving competition, and their predictions are as follows:
A said: B second, I third
B said: I am second, E is fourth
C said: I am first, D is second
D said: C last, I am third
E said: I am fourth, A is first
It is known that each player is only half right, and programming determines the ranking of the game.
analyze:
According to the example of the murderer above, it can be analyzed that each person said two conditions. There is one right and one wrong, that is, one 0 and one 1. The ranking of each player may be 1-5, so list all the rankings and judge whether they meet the half of the requirements.
Code:
#include <stdio.h>
int main()
{
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
for (a = 1; a <= 5; a++)
{
for (b = 1; b <= 5; b++)
{
for (c = 1; c <= 5; c++)
{
for (d = 1; d <= 5; d++)
{
for (e = 1; e <= 5; e++)
{
if (((b == 2) + (a == 3) == 1) && (((b == 2) + (e == 4)) == 1)
&& (((c == 1) + (d == 2)) == 1) && (((c == 5) + (d == 3)) == 1)
&& (((e == 4) + (a == 1)) == 1))
{
if(a*b*c*d*e == 120)
printf("a = %d;b = %d;c = %d;d =%d;e = %d\n", a, b, c, d, e);
}
}
}
}
}
}
return 0;
}
Summarize:
List all possible ordering situations, and then make it satisfy the final condition. The reason why the above is equal to 120 is that 1*2*3*4*5 = 120, to prevent two people from ranking in the same place.