Cow Contest
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 15478 | Accepted: 8617 |
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头牛,牛A可以打败牛B表示牛A总是可以打败牛B,现在给你m行关系,每行第一个数为A,第二个数为B,表示牛A可以打败牛B,现在需要你通过这m行来确定有多少牛的排名是可以确定的,输出可以确定排名的牛的个数,题目保证不会给你自相矛盾的数据。
样例解释:4-->3,4-->2,3-->2,1-->2,2-->5
牛的打败关系可以传递,即可以打败2的牛可以打败牛5,而牛2又可以打败牛5,所以牛2和牛5的排名可以确定,为第四和第五,牛4虽然可以打败牛3,但是牛3和牛1的关系却是不确定的,所以牛1,牛3,牛4的关系不能确定。
思路:把牛看成一个地点,牛1可以打败牛2表示有一条从1到2的长度为1的路,当然这条路是单向的,一开始把每两个牛之间的距离设置为无穷大,然后把已知的路存进dis数组,接着按最短路的思路跑一遍floyd,松弛所有的边,对牛A,如果某一头牛到牛A的距离小于无穷大或者牛A到某一头牛的距离小于无穷大,表示这两头牛之间的关系确定,此时sum++,如果牛A与所有的牛关系都判断完了得到sum==n-1,表示牛A和n-1头牛的关系都确定了,所以牛A的排名确定,ans++,每一头牛都判断一遍,最后就能得出ans了,如果你得到的sum==n+1,表示你没有去掉dis[A][A],这个计算了两次。
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#include<vector>
#include<set>
#include<cstdlib>
#include<map>
#include<deque>
#include<queue>
#include<list>
const int inf=0x3f3f3f3f;
const int MOD=1e9+7;
#define ll long long
#define ME0(x) memset(x,0,sizeof(x))
#define MEF(x) memset(x,-1,sizeof(x))
#define MEI(x) memset(x,inf,sizeof(x))
using namespace std;
int main()
{
int n,m,dis[105][105],s,e;
cin>>n>>m;
MEI(dis);
for(int n1=1;n1<=n;n1++)
{
dis[n1][n1]=0;
}
for(int m1=1;m1<=m;m1++)
{
cin>>s>>e;
dis[s][e]=1;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
for(int k=1;k<=n;k++)
{
if(dis[j][k]>dis[j][i]+dis[i][k])
{
dis[j][k]=dis[j][i]+dis[i][k];
}
}
}
}
int sum,ans=0;
for(int i=1;i<=n;i++)
{
sum=0;
for(int j=1;j<=n;j++)
{
if(dis[j][i]<inf&&i!=j)
{
sum++;
}
if(dis[i][j]<inf&&i!=j)
{
sum++;
}
}
if(sum==n-1)
{
ans++;
}
}
cout<<ans<<endl;
}