POJ3660:Cow Contest(最短路)

http://poj.org/problem?id=3660

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 ≤ AN; 1 ≤ BN; AB), 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

题意分析:

n头牛比赛,m个结果,每个结果a b代表a胜过b,求可以确定名次的有多少。

解题思路:

最开始我以为是拓扑排序,但是这样只能判断名次最高的几个和名次最低的几个,后来知道如果一个奶牛和其他所有奶牛的关系都确定了,那么它的位置就是一定的了。

先Floyd跑一边最短路,再判断一只奶牛是否和其他所有奶牛都有关系,即判断两者之间是否有路能够到达。

#include <stdio.h>
#include <string.h>
#define N 120
int e[N][N], n, m;

int main()
{
	int i, j, k, ans, u, v, sum, inf=99999999;
	while(scanf("%d%d", &n, &m)!=EOF)
	{
		ans=0;
		for(i=1; i<=n; i++)
			for(j=1; j<=n; j++)
				if(i==j)
					e[i][j]=0;
				else
					e[i][j]=inf;
		for(i=1; i<=m; i++)
		{
			scanf("%d%d", &u, &v);
			e[u][v]=1;	
		}
		for(k=1; k<=n; k++)
			for(i=1; i<=n; i++)
				for(j=1; j<=n; j++)
					if(e[i][k]+e[k][j]<e[i][j])
						e[i][j]=e[i][k]+e[k][j];
		for(i=1; i<=n; i++)
		{
			sum=0;
			for(j=1; j<=n; j++)
				if(e[i][j]!=inf || e[j][i]!=inf)
					sum++;
			if(sum==n)
				ans++;
		}
		printf("%d
", ans);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/zyq1758043090/p/11852599.html