Time Limit:?1000MS | ? | Memory Limit:?65536K |
Total Submissions:?7690 | ? | Accepted:?4288 |
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
剛才學了下閉包傳遞,簡單來說就是用Floyd來求兩點是否連通。這題里,如果一點的入度加上出度等于N-1,那么就可確定這點的等級,因為除了它自己之外的所有節點要么在它之前要么在它之后,不管它前面的節點后后面的節點怎么排序,都不會影響到它。
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 5 const int SIZE = 105; 6 int N,M; 7 int IN[SIZE],OUT[SIZE]; 8 bool G[SIZE][SIZE]; 9 10 int main(void) 11 { 12 int from,to; 13 int ans; 14 15 while(scanf("%d%d",&N,&M) != EOF) 16 { 17 fill(&G[0][0],&G[N][N],false); 18 for(int i = 0;i <= N;i ++) 19 IN[i] = OUT[i] = 0; 20 21 for(int i = 0;i < M;i ++) 22 { 23 scanf("%d%d",&from,&to); 24 G[from][to] = true; 25 } 26 27 for(int k = 1;k <= N;k ++) 28 for(int i = 1;i <= N;i ++) 29 for(int j = 1;j <= N;j ++) 30 G[i][j] = G[i][j] || G[i][k] && G[k][j]; 31 for(int i = 1;i <= N;i ++) 32 for(int j = 1;j <= N;j ++) 33 if(G[i][j]) 34 { 35 IN[j] ++; 36 OUT[i] ++; 37 } 38 39 ans = 0; 40 for(int i = 1;i <= N;i ++) 41 if(IN[i] + OUT[i] == N - 1) 42 ans ++; 43 printf("%d\n",ans); 44 } 45 46 return 0; 47 }
?