1. 程式人生 > >POJ 3660 Cow Contest(Floyd最短路)

POJ 3660 Cow Contest(Floyd最短路)

Cow Contest Time Limit: 1000MS Memory Limit: 65536K

Total Submissions: 10780 Accepted: 6003


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種奶牛之間的實力關係,如示例中給出5頭奶牛和5中實力關係,第一個是4號奶牛實力大於3號,第二個是4號奶牛實力大於2號。。。,求在這n個牛中實力能確定排名的有幾頭,如示例中1、3、4號牛實力大於2號,2號大於5號,則5號牛實力排名為第5名,2號牛為第4名,故輸出2,,


思路:如果一頭牛和其他n-1頭牛的實力關係確定,那麼這頭牛的排名也就確定了,但有可能兩頭牛之間的關係不是直接確定,而是通過其他牛確定,這樣就可以想到最短路演算法。。根據利害關係構成一個有向圖,然後用Floyd演算法確定任意兩頭牛之間的關係。。


AC程式碼:

#include<stdio.h>
#include<string.h>
int map[105][105];
int main(){
    int i,j,k;
    int m,n;
    int x,y;
    scanf("%d%d",&n,&m);
    memset(map,0,sizeof(map));
    for(i=0;i<m;i++){
        scanf("%d%d",&x,&y);
        map[x-1][y-1]=1;  ///減1是為了讓下標從0開始
    }

    for(k=0;k<n;k++)
        for(i=0;i<n;i++)
            for(j=0;j<n;j++){
        ///如果i能打敗k,k能打敗j,則i能打敗j
                if(map[i][k] && map[k][j])
                    map[i][j]=1;
            }

            int sum=0;
            for(i=0;i<n;i++){
                int tmp=0;
                for(j=0;j<n;j++){
                    if(map[i][j]|| map[j][i])///i和j之間是否存在利害關係
                        tmp++;
                }
                //printf("%d\n",tmp);
                if(tmp==n-1)
                    sum++;
            }

            printf("%d\n",sum);
    return 0;
}