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,b战胜c,即a战胜c,……胜负可以传递。
如有三头牛,a战胜c,a战胜b,输出结果为1.
分析:
如果其中一头牛被i头牛打败(e[i][x]),而战胜了j头牛(e[x][j]),则x+y = n-1;则这头牛的排名就确定了;
这个题需要利用传递闭包问题:
此题用来判断比赛中名次排列的。
传递闭包问题:一个有n个顶点的有向图的传递闭包为:邻接矩阵中e[i,j]表示i到j是否直接可达,若直接可达,则e[i,j]记为1,否则记为0;有向图的传递闭包表示从邻接矩阵e出发,求的所有节点间的路径可达情况,该矩阵就为所要求的传递闭包矩阵。
//传递闭包
void Warshll()
{
int i,j,k;
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
e[i][j] = e[i][j] || (e[i][k]&&e[k][j]);
}
}
}
代码
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int e[505][505];
int n,m;
//传递闭包
void Warshll()
{
int i,j,k;
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
e[i][j] = e[i][j] || (e[i][k]&&e[k][j]);
}
}
}
int main()
{
int i,j;
int A,B;
scanf("%d%d",&n,&m);
memset(e,0,sizeof(e));//初始化为0
for(i=1;i<=m;i++)
{
scanf("%d%d",&A,&B);
e[A][B]=1;//有向图,用1表示从i 到j可以连通。
}
Warshll();
int ans,res=0;
for(i=1;i<=n;i++)
{
ans=0;
for(j=1;j<=n;j++)
{
if(i==j)
continue;
else if(e[i][j]==1 || e[j][i]==1)//被打败和战胜的次数,i,j有两种情况,要么被i打败(失败),要么打败i(战胜);
ans++;
}
if(ans==n-1)
res++;
}
printf("%d\n",res);
return 0;
}