POJ3660 Cow Contest(Floyd+传递闭包)

POJ3660 Cow Contest(Floyd+传递闭包)

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

题意

有n头牛, 给你m对关系(a, b)表示牛a能打败牛b, 求在给出的这些关系下, 能确定多少牛的排名。
先讲一下关系闭包:
关系闭包有三种: 自反闭包(r), 对称闭包(s), 传递闭包(t)。
先画出 R 的关系图,再画出 r®, s®, t® 的关系图。
我们今天用的是传递闭包。仅作为个人理解 传递闭包:关系之间具有传递性(例如a> b, b> c, 那么a> c),在那些已给出的关系基础上,通过传递性,把所有可能的关系都找出来。
如果一头牛被x头牛打败,并且可以打败y头牛,如果x+y=n-1,则我们容易知道这头牛的排名就被确定了,所以我们只要将任一头牛,可以打败其他的牛的个数x, 和能打败该牛的牛的个数y求出来,在遍历所有牛判断一下是否满足x+y=n-1,就知道这个牛的排名是否能确定了(而传递闭包,正好将所有能得出关系都求出来了), 再将满足这个条件的牛数目加起来就是所求解。 x可以看成是入度, y是出度。
该段落出处https://www.cnblogs.com/wd-one/p/4545086.html

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
#include<functional> 
#include<map>
//#include<unordered_map>
#define lowbit(x) ((x)&-(x));
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N=1e5+10,NN=1e4+10,INF=0x3f3f3f3f,LEN=110;
const ll MOD=1e9+7;
const ull seed=31;
int n,m;
int gra[NN][NN];
void floyd(){
	for(int k=1;k<=n;k++){
		for(int i=1;i<=n;i++){
			if(gra[i][k]==INF) continue;
			for(int j=1;j<=n;j++) if(gra[k][j]!=INF) gra[i][j]=1;
		}
	}
}
void init(){
	for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) gra[i][j]=INF;
}
int main(){
	scanf("%d%d",&n,&m);
	init();
	for(int i=1;i<=m;i++){
		int u,v;
		scanf("%d%d",&u,&v);
		gra[u][v]=1;
	}
	floyd();
	int ans=0;
	for(int i=1;i<=n;i++){
		int sum=0;
		for(int j=1;j<=n;j++) if(gra[i][j]==1||gra[j][i]==1) ++sum;
		if(sum==n-1) ++ans;
	}
	printf("%d\n",ans);
}

猜你喜欢

转载自blog.csdn.net/Hc_Soap/article/details/107722342