POJ3660——Cow Contest(Floyd+传递闭包)
Cow Contest
Description
N (1 ≤ N ≤ 100) cows, conveniently numbered 1..N, are participating in a programming contest. As we all know, some cows code better than others. Each cow has a certain constant skill rating that is unique among the competitors.
The contest is conducted in several head-to-head rounds, each between two cows. If cow A has a greater skill level than cow B (1 ≤ A ≤ N; 1 ≤ B ≤ N; A ≠ B), then cow A will always beat cow B.
Farmer John is trying to rank the cows by skill level. Given a list the results of M (1 ≤ M ≤ 4,500) two-cow rounds, determine the number of cows whose ranks can be precisely determined from the results. It is guaranteed that the results of the rounds will not be contradictory.
Input
* Line 1: Two space-separated integers: N and M
* Lines 2..M+1: Each line contains two space-separated integers that describe the competitors and results (the first integer, A, is the winner) of a single round of competition: A and B
Output
* Line 1: A single integer representing the number of cows whose ranks can be determined
Sample Input
5 5
4 3
4 2
3 2
1 2
2 5
Sample Output
2
题目大意:
给一些牛的排名关系,问有多少牛的排名确定。
解题思路:
使用Floyd算法来判断传递闭包。
首先通过输入信息建立邻接矩阵,再使用Floyd求出最短路径Edge[i][j]。
这时,相对于牛i若Edge[i][j]存在,则说明i肯定打不过j。若Edge[j][i]存在则说明i肯定打得过牛j。
若i肯定能打过的牛和肯定打不过的牛的和等于牛的总和N-1,则牛i的位置确定。
据说这个东西叫做传递闭包--!
Code:
1 #include<stdio.h> 2 #include<string> 3 #include<iostream> 4 #define MAXN 300 5 using namespace std; 6 int edge[MAXN+10][MAXN+10]; 7 int N,M; 8 void init() 9 { 10 for (int i=1; i<=N; i++) 11 for (int j=1; j<=N; j++) 12 edge[i][j]=INT_MAX; 13 } 14 void floyd() 15 { 16 int m,i,j; 17 for (m=1; m<=N; m++) 18 for (i=1; i<=N; i++) 19 for (j=1; j<=N; j++) 20 { 21 if (edge[i][m]!=INT_MAX&&edge[m][j]!=INT_MAX&&edge[i][j]>edge[i][m]+edge[m][j]) 22 edge[i][j]=edge[i][m]+edge[m][j]; 23 } 24 } 25 int main() 26 { 27 while (cin>>N>>M) 28 { 29 init(); 30 for (int i=1; i<=M; i++) 31 { 32 int x1,x2; 33 scanf("%d %d",&x1,&x2); 34 edge[x1][x2]=1; 35 } 36 floyd(); 37 int sum=0; 38 for (int i=1; i<=N; i++) 39 { 40 int cnt=0; 41 for (int j=1; j<=N; j++) 42 { 43 if (i!=j&&edge[i][j]!=INT_MAX) 44 cnt++; 45 if (i!=j&&edge[j][i]!=INT_MAX) 46 cnt++; 47 } 48 if (cnt==N-1) sum++; 49 } 50 printf("%d\n",sum); 51 } 52 return 0; 53 }