题目:http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2819
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <algorithm> 6 using namespace std; 7 const int maxn = 800+10; 8 int t, head[maxn], cnt[maxn], a[maxn]; 9 10 struct node 11 { 12 int u, v, next; 13 } g[maxn]; 14 void init() 15 { 16 t = 0; 17 memset(head, -1, sizeof(head)); 18 memset(cnt, 0, sizeof(cnt)); 19 } 20 void add(int u, int v) 21 { 22 g[t].u = u; 23 g[t].v = v; 24 g[t].next = head[u]; 25 head[u] = t; 26 t++; 27 } 28 void topo(int u) 29 { 30 int i; 31 for(i = head[u]; i != -1; i = g[i].next) 32 cnt[g[i].v]--; 33 } 34 int main() 35 { 36 int n, m, p1, p2, f; 37 int i, j, x; 38 while(~scanf("%d%d", &n, &m)) 39 { 40 f = 0; 41 x = 1; 42 init(); 43 while(m--) 44 { 45 scanf("%d%d", &p1, &p2); 46 add(p1, p2); //有向边 47 cnt[p2]++; 48 } 49 for(i = 1; i <= n; i++) 50 { 51 for(j = 1; j <= n; j++) 52 { 53 if(cnt[j]==0) 54 { 55 cnt[j] = -1; 56 a[x++] = j; 57 topo(j); //拓扑排序,去掉入度 58 break; 59 } 60 } 61 if(j == n+1) //如果没有入度为0的,说明不符合条件 62 { 63 f = 1; 64 break; 65 } 66 } 67 if(f) 68 printf("-1 "); 69 else 70 { 71 for(i = 1; i <= n; i++) 72 if(i==n) 73 printf("%d ", a[i]); 74 else 75 printf("%d ", a[i]); 76 } 77 } 78 return 0; 79 }