Input data:
4 6
1 2
1 3
2 3
3 4
2 4
4 2
4 6
1 2
1 3
2 3
3 4
2 4
1 2
Topo sort to partial order:
Demo: http://www.tyut.edu.cn/kecheng1/site01/suanfayanshi/topological_sort.asp
Details: http://blog.csdn.net/dm_vincent/article/details/7714519
1#include <stdio.h>2#include <queue>3#include <string.h>4 using namespacestd;5 intindegree[ -] ;6queue<int>Q;7 intN, M;8 BOOLmap[ -][ -] ;9 inta[ -] ;Ten intTopointN) One { A intCNT =0 ; - while(!q.empty ()) - Q.pop (); the - for(inti =1; I <= N; i++) { - if(Indegree[i] = =0) { -Q.push (i);//A point with an entry of 0 is the starting point + } - } + A inttemp; at while(!Q.empty ()) { -temp =Q.front (); -A[cnt + +] =temp; - Q.pop (); - for(inti =1; I <= N; i++) { - if(Map[temp][i]) { inindegree[i]--; - if(Indegree[i] = =0) to Q.push (i); + } - } the } * if(cnt = = N)//output has loop information when the number of vertices in the output is less than the number of vertices in the graph $ for(inti =0; I < n; i++) {Panax Notoginsengprintf ("%d----->", A[i]); - } the Else +Puts ("The network has a cycle!") ; A } the + intMain () - { $ //freopen ("A.txt", "R", stdin); $ intu, v; - while(~ scanf ("%d%d", &n, &m)) { -memset (Indegree,0,sizeof(Indegree)); thememset (Map,0,sizeof(map)); - for(inti =0; I < m; i++) {Wuyiscanf ("%d%d", &u, &v); the if(!map[u][v])//when u and V are not connected -indegree[v]++;//entry of Point V + + WuMAP[U][V] =1;//indicates connectivity - } About topo (n); $ } -}
View Code
Topo Sort full version