POJ3660——Cow Contest(Floyd+传递闭包)

时间:2022-06-19 19:30:15

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:

 #include<stdio.h>
#include<string>
#include<iostream>
#define MAXN 300
using namespace std;
int edge[MAXN+][MAXN+];
int N,M;
void init()
{
for (int i=; i<=N; i++)
for (int j=; j<=N; j++)
edge[i][j]=INT_MAX;
}
void floyd()
{
int m,i,j;
for (m=; m<=N; m++)
for (i=; i<=N; i++)
for (j=; j<=N; j++)
{
if (edge[i][m]!=INT_MAX&&edge[m][j]!=INT_MAX&&edge[i][j]>edge[i][m]+edge[m][j])
edge[i][j]=edge[i][m]+edge[m][j];
}
}
int main()
{
while (cin>>N>>M)
{
init();
for (int i=; i<=M; i++)
{
int x1,x2;
scanf("%d %d",&x1,&x2);
edge[x1][x2]=;
}
floyd();
int sum=;
for (int i=; i<=N; i++)
{
int cnt=;
for (int j=; j<=N; j++)
{
if (i!=j&&edge[i][j]!=INT_MAX)
cnt++;
if (i!=j&&edge[j][i]!=INT_MAX)
cnt++;
}
if (cnt==N-) sum++;
}
printf("%d\n",sum);
}
return ;
}