poj 3660 Cow Contest(用floyd的传递闭包)

                                                                              Cow Contest
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 14455   Accepted: 8097

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 ≤ AN; 1 ≤ BN; AB), 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种两头牛之间的关系; 然后接下来给你这m种关系,每种关系有a, b两个数构成,表示a牛可以击败b牛;现在问这n头牛有几头牛的排名能够确定;
//比如案例中的2号牛和5号牛,分别就是倒数第二,和倒数第一,这两个可以确定,所以输出2;

//理解:如果当前牛与其他所有牛都有关系(直接或者间接),那么这头牛的排名就可以确定,这是本题的核心(画案例中的图就知道);构建一个关系图,通过floyd算法来完成这n个点之间的闭包关系;
#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cstring>
#include<vector>
#include<cmath>
#define maxn 105
using namespace std;
int G[maxn][maxn];
int n, m;

void floyd(){
    for(int k = 1; k <= n; k++){
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= n; j++){ //看看任意两头牛的关系如何,如果有关系值就是1(包括之间关系和间接关系)
                G[i][j] = G[i][j] || (G[i][k]&&G[k][j]);  //前面G[i][j]表示i,j有直接关系,(G[i][k]&&G[k][j])表示i,j可以通过其他牛找到间接关系;
            }
        }
    }
    return;
}

int main(){
    int a, b;
    while(scanf("%d%d", &n, &m) != EOF){
        for(int i = 0; i <= n; i++){
            for(int j = 0; j <= n; j++)
                G[i][j] = 0;
        }
        for(int i = 0; i < m; i++){
            scanf("%d%d", &a, &b);
            G[a][b] = 1;
        }
        for(int i = 1; i <= n; i++){ //自己和自己有关系,这一步不能丢了!
            G[i][i] = 1;
        }
        floyd();
        int flag = 1;
        int ans = 0;
        for(int i = 1; i <= n; i++){
            flag = 1;
            for(int j = 1; j <= n; j++){ //对于第i头牛,我们通过这个for循环看看它是不是和其他所有牛都有关系;
                flag = flag && (G[i][j] || G[j][i]); //只要有一个关系不能确定,flag就是0,只有所有关系都确定是flag的值才是1;
            }
            if(flag)
                ans++;  //能够与所有牛确定关系的牛有几头;
        }
        cout << ans << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/guihaiyuan123/article/details/80152492