Tic-tac-toe
time limit per test
1 second
memory limit per test
64 megabytes
Certainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a 3 × 3grid (one player always draws crosses, the other — noughts). The player who succeeds first in placing three of his marks in a horizontal, vertical or diagonal line wins, and the game is finished. The player who draws crosses goes first. If the grid is filled, but neither Xs, nor 0s form the required line, a draw is announced.
You are given a 3 × 3 grid, each grid cell is empty, or occupied by a cross or a nought. You have to find the player (first or second), whose turn is next, or print one of the verdicts below:
- illegal — if the given board layout can't appear during a valid game;
- the first player won — if in the given board layout the first player has just won;
- the second player won — if in the given board layout the second player has just won;
- draw — if the given board layout has just let to a draw.
Input
The input consists of three lines, each of the lines contains characters ".", "X" or "0" (a period, a capital letter X, or a digit zero).
Output
Print one of the six verdicts: first, second, illegal, the first player won, the second player won or draw.
今天算是见识到了CodeForces的数据,有个小伙伴wa在了text 120....
于是写之前想了很多种情况
判断的优先级:
illegal-->first win/second win--> draw --> first/second
#include
#include
#include
using namespace std;
int a[3][3];
bool check(int x)
{
for (int i = 0; i < 3; i++)
{
int j;
for (j = 0; j < 3; j++)
if (a[i][j] != x) break;
if (j == 3) return 1;
}
for (int j = 0; j < 3; j++)
{
int i;
for (i = 0; i < 3; i++)
if (a[i][j] != x) break;
if (i == 3) return 1;
}
if (a[0][0] == x && a[1][1] == x && a[2][2] == x) return 1;
if (a[0][2] == x && a[1][1] == x && a[2][0] == x) return 1;
return 0;
}
int main()
{
char c;
int n1=0, n2 = 0;
for (int i = 0; i < 3;i++)
for (int j = 0; j < 3; j++)
{
cin >> c;
if (c == '.') a[i][j] = 0;
if (c == 'X')
{
a[i][j] = 1;
n1++;
}
if (c == '0')
{
a[i][j] = 2;
n2++;
}
}
if (n1 - n2 > 1 || n2>n1)
{
printf("illegal\n");
return 0;
}
bool w1 = 0, w2 = 0;
w1 = check(1);
w2 = check(2);
int next;
if (n1 > n2) next = 2;
else next = 1;
if (w1 && w2)
{
printf("illegal\n");
return 0;
}
if (w1 && next==1)
{
printf("illegal\n");
return 0;
}
if (w2 && next == 2)
{
printf("illegal\n");
return 0;
}
if (w1)
{
printf("the first player won\n");
return 0;
}
if (w2)
{
printf("the second player won\n");
return 0;
}
if (n1 + n2 == 9)
{
printf("draw\n");
return 0;
}
if (next==1)
{
printf("first\n");
return 0;
}
if (next == 2)
{
printf("second\n");
return 0;
}
}