POJ3660 Cow Contest【Floyd演算法 傳遞閉包】

Enjoy_process發表於2018-10-19

Cow Contest

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 16316   Accepted: 9126

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 ≤ NA ≠ 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

Source

USACO 2008 January Silver

問題連結:POJ3660 Cow Contest

問題描述:有n個奶牛(從1開始編號)進行比賽,有m個結果,一個結果用a b描述,表示a奶牛打敗b奶牛,在這種情況下a奶牛也能打敗b奶牛能打敗的奶牛,問通過這m個結果能確定多少個奶牛的名次。

解題思路:共有n奶牛,如果能打敗奶牛a的奶牛有x個,能被奶牛打敗的奶牛有y個,且x+y=n-1那麼奶牛a的名次就是確定的,且其名次為第x+1名。傳遞閉包,使用Floyd演算法進行求解

AC的C++程式:

#include<iostream>
#include<cstring>

using namespace std;
const int N=105;
bool r[N][N];//r[i][j]表示奶牛i能打敗奶牛j

int main()
{
	int n,m,i,j,k,a,b;
	scanf("%d%d",&n,&m);
	memset(r,false,sizeof(r));
	while(m--){
		scanf("%d%d",&a,&b);
		r[a][b]=true;//a能打敗b 
	}
	for(k=1;k<=n;k++)
	  for(i=1;i<=n;i++)
	    for(int j=1;j<=n;j++)
	    	if(r[i][k]&&r[k][j])//i能打敗k,k能打敗j,則i就能打敗j;閉包傳遞 
	    	  r[i][j]=true;
	int ans=0;
	for(i=1;i<=n;i++){
		for(j=1;j<=n;j++){
	  		if(i==j) continue;
	  		if(r[i][j]==false&&r[j][i]==false) break;//不能夠確定i和j的關係 
	  	}
	  	if(j>n)
	    	ans++;
	}
	printf("%d\n",ans);
	return 0;
} 


 

相關文章