拓扑排序,居然要考虑重边,使用STL实现。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 7 #define MAXNUM 505 8 9 char map[MAXNUM][MAXNUM]; 10 int node[MAXNUM]; 11 priority_queue<int, vector<int>, greater<int> > teams; 12 13 int main() { 14 int n, m, a, b; 15 int i, j; 16 17 while (scanf("%d%d", &n, &m) != EOF) { 18 memset(node, 0, sizeof(node)); 19 memset(map, 0, sizeof(map)); 20 21 for (i=0; i<m; ++i) { 22 scanf("%d %d", &a, &b); 23 if (map[a][b] == 0) 24 node[b]++; 25 map[a][b] = 1; 26 } 27 for (i=1; i<=n; ++i) 28 if (node[i] == 0) 29 teams.push(i); 30 j = 0; 31 while ( !teams.empty() ) { 32 a = teams.top(); 33 teams.pop(); 34 if (j == 0) { 35 printf("%d", a); 36 j = 1; 37 } else 38 printf(" %d", a); 39 for (i=1; i<=n; ++i) 40 if (map[a][i]) { 41 node[i]--; 42 if (node[i] == 0) 43 teams.push(i); 44 } 45 } 46 printf(" "); 47 } 48 49 return 0; 50 }