http://acm.hdu.edu.cn/showproblem.php?pid=2647
View Code
1 #include<iostream> 2 #include<cstring> 3 using namespace std ; 4 #define M 10005 5 struct node 6 { 7 int degree ; 8 int v ; 9 int money ; 10 node *next ; 11 }s[M] ; 12 int q[M*100], mark[M] ; 13 int find(int a, int b) 14 { 15 node *p = new node ; 16 for(p=s[a].next; p!=NULL; p=p->next) 17 if(p->v==b) 18 return 1 ; 19 return 0 ; 20 } 21 int add(int a, int b) 22 { 23 if(!find(a,b)) 24 { 25 node *p = new node ; 26 p->next = s[a].next ; 27 p->v = b ; 28 s[a].next = p ; 29 s[b].degree++ ; 30 } 31 return 0 ; 32 } 33 int topological(int n) 34 { 35 int i, k, l, h, ans = 0, flag = 0 ; 36 l = h = 0 ; 37 for(i=1; i<=n; i++) 38 if(mark[i]) 39 { 40 flag = 1 ; 41 if(s[i].degree==0) 42 q[l++] = i ; 43 } 44 if(flag&&l==0) 45 return -1 ; 46 node *p = new node ; 47 while(h<l) 48 { 49 k = q[h++] ; 50 ans += s[k].money ; 51 for(p=s[k].next; p!=NULL; p=p->next) 52 { 53 if(s[p->v].degree>0) 54 { 55 s[p->v].degree-- ; 56 s[p->v].money = s[k].money+1 ; 57 if(s[p->v].degree==0) 58 q[l++] = p->v ; 59 } 60 } 61 62 } 63 for(i=1; i<=n; i++) 64 if(mark[i]&&s[i].degree) 65 return -1 ; 66 for(i=1; i<=n; i++) 67 if(!mark[i]) 68 ans += 888 ; 69 return ans ; 70 } 71 int main() 72 { 73 int n, m, i, x, y ; 74 while(cin>>n>>m) 75 { 76 for(i=1; i<=n; i++) 77 { 78 s[i].next = NULL ; 79 s[i].degree = 0 ; 80 s[i].money = 888 ; 81 mark[i] = 0 ; 82 } 83 while(m--) 84 { 85 cin>>x>>y ; 86 add(y, x) ; 87 mark[x] = mark[y] = 1 ; 88 89 } 90 int tosort = topological(n) ; 91 cout<<tosort<<endl ; 92 } 93 return 0 ; 94 }
多看几遍,好好理解