标签:
拓扑排序是对ADG(有向无环图进行线性排序)
模板:
队列实现
#include<cstdio> #include<cstring> #include<algorithm> #include<queue> using namespace std; int indegree[100]; queue<int> q; int n,m; bool map[100][100]; int a[100]; int topo(int n) { int cnt = 1; while(!q.empty()) q.pop(); for(int i = 1; i <= n ; i++) if(indegree[i] == 0) q.push(i); int u; while(!q.empty()){ u = q.front(); a[cnt++] = u; q.pop(); for(int i = 1; i <= n ; i++){ if(map[u][i]){ indegree[i] --; if(indegree[i] == 0) q.push(i); } } if(cnt == n){ for(int i = 1 ; i <= n ; i++) printf(" %d",a[i]); } else printf("The network has a cycle"); } } int main() { int u,v; while(~scanf("%d%d",&n,&m)){ memset(indegree,0,sizeof(indegree)); memset(map,0,sizeof(map)); for(int i = 0 ; i < m ; i++){ scanf("%d%d",&u,&v); if(!map[u][v]) indegree[v]++; map[u][v] = 1; } topo(n); } return 0; }
邻接表实现
#include<cstdio> #include<cstring> #include<algorithm> #include<queue> using namespace std; const int M = 100005; struct Edge { int v,nxt; Edge() {} Edge(int v,int nxt): v(v),nxt(nxt){} }e[M]; int head[M],E; int a[M]; int indegree[M]; int n,m,u,v; void addedge() { e[E] = Edge(v, head[u]); head[u] = E++; } void inti() { E = 0; memset(head,-1,sizeof(head)); memset(a,0,sizeof(a)); memset(indegree,0,sizeof(indegree)); } void topo(int n) { queue<int> q; int cnt = 1; while(!q.empty()) q.pop(); for(int i = 1; i <= n ; i++) if(indegree[i] == 0 ) q.push(i); while(!q.empty()){ int u = q.front(); a[cnt++] = u; q.pop(); for(int i = head[u]; ~u; i = e[i].nxt){ indegree[e[i].v]--; if(indegree[e[i].v] == 0 ) q.push(e[i].v); } } } int main() { while(~scanf("%d%d",&n,&m)){ for(int i = 1; i <= m ; i++){ scanf("%d%d",&u,&v); indegree[v]++; addedge(); } topo(n); } return 0; }
标签:
原文地址:http://www.cnblogs.com/zero-begin/p/4471084.html