1 2 4 3
思路:因为要满足字典序的拓扑排序,所以用了STL中的优先队列。
priority_queue<int,vector<int>, greater<int> > Q;
实现了权值小的优先级高,取出的时候保证序号是队列中最小的。
其他的和一般的拓扑排序无区别。
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<queue> #include<vector> using namespace std; const int MAXN = 550; const int MAXM = 25000; int head[MAXN],indegree[MAXN],ans[MAXN],N,M; struct EdgeNode { int to; int w; int next; }; EdgeNode Edges[MAXM]; int toposort() { priority_queue<int,vector<int>, greater<int> > Q; for(int i = 1; i <= N; i++) { if(indegree[i]==0) Q.push(i); } int id = 0; while(!Q.empty()) { int u; ans[id++] = u = Q.top(); Q.pop(); for(int k = head[u]; k != -1; k = Edges[k].next) { indegree[Edges[k].to]--; if(!indegree[Edges[k].to]) { Q.push(Edges[k].to); } } } if(id == N) { for(int i = 0; i < id; i++) { if(i != id-1) cout << ans[i] << " "; else cout << ans[i] << endl; } } else return 0; } int main() { int x,y; while(cin >> N >> M) { memset(ans,0,sizeof(ans)); memset(head,-1,sizeof(head)); memset(Edges,0,sizeof(Edges)); for(int i = 0; i < M; i++) { cin >> x >> y; Edges[i].to = y; Edges[i].w = 1; Edges[i].next = head[x]; head[x] = i; indegree[y]++; } toposort(); } return 0; }