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,表示n头牛,m个比赛结果
接下来m行,每行A,B两个数字每行表示A牛赢了B牛,问有几头牛可以确定排名
具体思路
放在了最短路里的一题,第一眼看去很像拓扑排序,在后台数据中存在自环数据,拓扑排序个人比较不擅长,跑去学了一手传递闭包的思想,在这里其实就是计算有几头牛赢了自己,自己又赢了几头牛,加起来如果等于n-1就是固定的排位,利用这个思想跑floyd的板子,就可以找到每一头牛赢其他牛的状态,相反这头牛被某头牛赢了就是输给了某头牛,一个最短路板子跑一下,计算一下数字就可以了
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,m;
int line[105][105];
void floyd()
{
for (int i=1;i<=n;i++)
{
for (int j=1;j<=n;j++)
{
for (int k=1;k<=n;k++)
{
if (line[j][i]==1&&line[i][k]==1)
{
line[j][k]=1;
}
}
}
}
}
int main()
{
scanf("%d %d",&n,&m);
memset(line,0,sizeof(line));
for (int i=0;i<m;i++)
{
int from,to;
scanf("%d %d",&from,&to);
line[from][to]=1;
}
floyd();
int ans=0;
for (int i=1;i<=n;i++)
{
int num=0;
for (int j=1;j<=n;j++)
{
num+=line[i][j]+line[j][i];
}
if (num==n-1)
{
ans++;
}
}
printf("%d\n",ans);
return 0;
}