ACM: 动态规划题 sicily…

来源:互联网 发布:java酒店管理系统程序 编辑:程序博客网 时间:2024/05/23 12:54

1822. Fight Club

Description

Fightclub is an organization where you release your pressure and emotionby fighting the other club members. The fight begins like this: npeople standing in a circle. Then two adjacent guys are chosen tofight. The winner will stay and the loser will be sent to thehospital (there is no tie in the fighting). The cruel fightcontinues 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 everypair of fighters. Though they enjoy fighting, they still want to bethe winner. You are to tell each of them, if the fight is arrangedproperly, can he be the winner.

Input

First line contains integer T (T<=5), the numberof 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 lineseach contains n ‘0’ or ‘1’, separated by a single blank. The ithnumber in jth line indicates the fighting result of ith and jthfighter. If it is ‘1’, then the ith fighter will always beat thejth fighter, otherwise he will always lose. You can safely assumethat aij and aji are different and aii=0 for every distinct i andj.
The people are numbered counterclockwise. 

Output

For each test case, output n lines. If the ith fighter can bethe 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

Sample Output

1
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;
}
0 0
原创粉丝点击