Cow Contest(最短路floyed传递闭包)

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 ≤ NA≠ 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场比赛,位置在前面的是胜利的牛的编号,如果一头牛和剩下的牛都能确定等级关系,说明可以去确定该牛的等级
,求出可以确定等级的牛的个数

解题思路:这是一个利用最短路floyed算法的一个传递闭包问题,如果一个点和其余各点都确定关系了,那么这个点的等级就可以确定了。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,m;
int map[200][200];
int floyd()
{
    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]=1;///如果任意两个点能够通过第三个点发生关系,那么说明这两个点也是有关系的
                }
            }
}
int main()
{
    int a,b,i,j,count,sum;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(map,0,sizeof(map));
        for(i=0; i<m; i++)
        {
            scanf("%d%d",&a,&b);
            map[a][b]=1;///可以确定关系的利用邻接矩阵记录为1
        }
        floyd();
        count=0;
        for(i=1; i<=n; i++)
        {
            sum=0;
            for(j=1; j<=n; j++)
            {
                if(map[i][j]||map[j][i])
                {
                    sum++;
                }
            }
            if(sum==n-1)///如果一个点和其余各点的关系确定,那么这个点就可以确定等级
            {
                count++;
            }
        }
        printf("%d
",count);
    }
    return 0;
}

  



原文地址:https://www.cnblogs.com/wkfvawl/p/9245187.html