确定比赛名次 HDU - 1285 (拓扑排序)
注意点: 输入数据中可能有重复,需要进行处理!
1 #include <stdio.h>
2 #include <iostream>
3 #include <cstring>
4 #include <vector>
5 #include <algorithm>
6 #include <sstream>
7
8
9 using namespace std;
10
11 int n, m;
12
13 int g[501][501];
14 int indegree[501]; // 入度
15 int r[501];
16
17 int main()
18 {
19 while(scanf("%d %d", &n, &m) != EOF)
20 {
21 memset(g, 0, sizeof(g));
22 memset(indegree, 0, sizeof(indegree));
23
24 for(int i = 1; i <= m; ++i)
25 {
26 int a, b;
27 scanf("%d %d", &a, &b);
28 if(g[a][b] == 0) // 输入数据中可能有重复输入!!!
29 {
30 g[a][b] = 1;
31 indegree[b]++;
32 }
33 }
34
35 for(int k = 1; k <= n; ++k)
36 {
37 int i, j;
38 for(i = 1; i <= n; ++i)
39 {
40 if(indegree[i] == 0)
41 {
42 indegree[i] = -1;
43 r[k] = i;
44 break;
45 }
46 }
47
48 for(j = 1; j <= n; ++j)
49 {
50 if(g[i][j] == 1)
51 {
52 g[i][j] = 0;
53 indegree[j]--;
54 }
55 }
56 }
57
58 for(int i = 1; i < n; ++i)
59 cout << r[i] << ' ';
60 cout << r[n] << endl;
61 }
62
63
64 return 0;
65 }