拓扑排序

拓扑排序

要用list,不能用vector,确保删除边的开销为O(1)。

因为主循环中,总共要从队列中pop掉n个数(点),然后总共要删e条边,删点和边的开销都是O(1)。所以整个时间复杂度就是O(n+e)。

如果最终还剩下边,证明存在环,sort失败。

 1 bool sort(list<pair<int, int> > &graph, int n, vector<int> &ans) {
 2     vector<int> prev(n, 0);
 3     for (auto it = graph.begin(); it != graph.end(); it++) {
 4         prev[it->second]++;
 5     }
 6 
 7     queue<int> q;
 8     for (int i = 0; i < n; ++i) {
 9         if (prev[i] == 0) q.push(i);
10     }
11 
12     while (!q.empty()) {
13         int top = q.front();
14         q.pop();
15         ans.push_back(top);
16 
17         for (auto it = graph.begin(); it != graph.end(); ) {
18             if (it->first == top) {
19                 prev[it->second]--;
20                 if (prev[it->second] == 0) q.push(it->second);
21                 it = graph.erase(it);
22             } else {
23                 it++;
24             }
25         }
26     }
27 
28     return graph.empty();
29 }
原文地址:https://www.cnblogs.com/linyx/p/4007773.html