码迷,mamicode.com
首页 > 其他好文 > 详细

拓扑排序

时间:2014-10-06 01:05:49      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   sp   div   c   on   log   

拓扑排序

要用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 }

 

拓扑排序

标签:style   blog   color   for   sp   div   c   on   log   

原文地址:http://www.cnblogs.com/linyx/p/4007773.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!