1822. Fight Club
Description
Fight club is an organization where you release your pressure and emotion by fighting the other club members. The fight begins like this: n people standing in a circle. Then two adjacent guys are chosen to fight. The winner will stay and the loser will be sent to the hospital (there is no tie in the fighting). The cruel fight continues until there is only one left.
It is somewhat strange to see that when two guys fight each other, the result is always definite, and you know the result of every pair of fighters. Though they enjoy fighting, they still want to be the winner. You are to tell each of them, if the fight is arranged properly, can he be the winner.
Input
First line contains integer T (T<=5), the number of test cases.
For each test case, the first line contains n (1<=n<=40), the number of people. Following is the description of a n*n matrix A. Following n lines each contains n ‘0’ or ‘1’, separated by a single blank. The ith number in jth line indicates the fighting result of ith and jth fighter. If it is ‘1’, then the ith fighter will always beat the jth fighter, otherwise he will always lose. You can safely assume that aij and aji are different and aii=0 for every distinct i and j.
The people are numbered counterclockwise.
Output
For each test case, output n lines. If the ith fighter can be the survivor, output 1, otherwise output 0.
Output a blank line after each test case.
Sample Input
2
2
0 1
0 0
3
0 1 1
0 0 1
0 0 0
2
0 1
0 0
3
0 1 1
0 0 1
0 0 0
Sample Output
1
0
1
0
0
0
1
0
0
题意: 一群人决斗, 给出一个人与另一个人决斗的胜负关系, 问结果合理决策每个人是否可以胜利.
解题思路:
1. 假设判断第i人是否可以胜出, 将第i人拆成2个人, 可以得出, 只要第i人能够与自己相遇
那么第i人就可以胜利.
2. 设dp[i][j]表示第i人是否可以与第j人相遇, g[i][j]表示第i人与第j的决斗胜负关系.
(1). dp[i][j] = 能够相遇; 满足: dp[i][k]&&dp[j][k]&&(g[i][k]||g[j][k])
(2). dp[i][j] = 不能相遇;
3. 因为n个人围成一个圆, 我们可以扩大一倍人数, 方便计算i 等价 i+n;
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 105
#define MAXSIZE 41
int n;
int g[MAXSIZE][MAXSIZE];
int dp[MAX][MAX];
void DP()
{
memset(dp, 0, sizeof(dp));
int N = 2*n-1;
int i, j, k;
for(i = 0; i < N; ++i)
dp[i][i+1] = 1;
for(k = 2; k <= n; ++k)
{
for(i = 0; i <= N-k; ++i)
{
for(j = i+1; j < i+k; ++j)
{
if( dp[i][j] && dp[j][i+k] )
{
int x1 = i%n;
int x2 = j%n;
int x3 = (i+k)%n;
if( g[x1][x2] || g[x3][x2] )
{
dp[i][i+k] = 1;
}
}
}
}
}
}
int main()
{
int i, j;
//freopen("input.txt", "r", stdin);
int caseNum;
scanf("%d", &caseNum);
while( caseNum-- )
{
scanf("%d", &n);
for(i = 0; i < n; ++i)
{
for(j = 0; j < n; ++j)
scanf("%d", &g[i][j]);
}
DP();
for(i = 0; i < n; ++i)
{
if(dp[i][i+n] == 1)
printf("1\n");
else
printf("0\n");
}
printf("\n");
}
return 0;
}