Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6098 | Accepted: 3302 |
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
Source
题目的 意思:有很多奶牛,等级有高有低,等级高的可以打得过等级低的,让你通过已知的输入求得有哪些奶牛的排名可以确定。
分析 :这里只要求出 能够打败的和不能打败的个数有n-1个 那么这个奶牛的排名就可以被确定。
通过这题学了一个新东西——“传递闭包”,是从网上搜到的
在此摘抄下来:
-------------------------
今天有人提到了传递闭包,我简单说说吧。
所谓传递性,可以这样理解:对于一个节点i,如果j能到i,i能到k,那么j就能到k。求传递闭包,就是把图中所有满足这样传递性的节点都弄出来,计算完成后,我们也就知道任意两个节点之间是否相连。
传递闭包的计算过程一般可以用Warshell算法描述:
For 每个节点i Do
其中a数组为布尔数组,用来描述两个节点是否相连,可以看做一个无权图的邻接矩阵。可以看到,算法过程跟Floyd很相似,三重循环,枚举每个中间节点。只不过传递闭包只需要求出两个节点是否相连,而不用求其间的最短路径长。
-------------------------
代码有点类似于floyd()算法,判断语句注意顺序#include<iostream>
#include<string>
using namespace std;
bool map[500][500];
void f(int n)
{
int i, j, k;
for(k = 1; k <= n; k++)
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
if((map[i][k] && map[k][j]))
map[i][j] = true;
}
int main()
{
int sum,i,num;
int a,b,m,n,j;
memset(map,false,sizeof(map));
sum=0;
cin>>n>>m;
while(m--)
{
scanf("%d %d",&a,&b);
map[a][b]=true;
}
f(n);
for(i=1;i<=n;i++)
{
num=0;
for(j=1;j<=n;j++)
{
if(map[i][j]||map[j][i])//找到他能打得赢的和打不赢的个数
num++;
}
if(num==n-1)
{
sum++;
}
}
cout<<sum<<endl;
}