当前位置:   article > 正文

BFS—拓扑排序_bfs拓扑排序

bfs拓扑排序

拓扑排序是bfs的一个简单的运用,具体实现的思路如下;

先将入度为0的点放入队列,然后取出对头,用对头更新其他点的入度,如果发现新的点的入度为0,则将该点放入队列,如此循环,直到队列为空;

要注意,有环图一定无拓扑排序,所以拓扑排序的一个简单运用为判断一个图是否为有环图。

这个可以用反证法;

假定一个有环图存在拓扑排序;

入队的某一时刻,记A环中的Q点为此环中的一个入队的点,说明此刻该点的入度为0,有因为Q点是第一个入队,说明环中指向它的P点未入队,P点未入队说明Q点的入度>=1,与入队的条件和第一个入队冲突;

故有环图不存在拓扑排序;

接下来是代码和注释。

 

  1. #include<iostream>
  2. #include<vector>
  3. #include<queue>
  4. #include<algorithm>
  5. using namespace std;
  6. const int N = 100010;
  7. struct poi {
  8. vector<int> ne;//ne中存储下一个点的下标
  9. int d = 0;//点的入度
  10. }pos[N];
  11. int p[N], fur;//存储点的拓扑排序
  12. int n, m;//n个点,m条边
  13. bool bfs() {
  14. queue<int> que;
  15. for (int i = 1; i <= n; i++) {//初始化队列,将所有入度为0的点放入队列
  16. if (!pos[i].d)
  17. que.push(i);
  18. }
  19. while (que.size()) {
  20. int t = que.front();
  21. p[fur++] = t;//将对头加入拓扑排序中
  22. que.pop();
  23. for (int i = 0; i < pos[t].ne.size(); i++) {//更新点的入度
  24. int m = pos[t].ne[i];
  25. pos[m].d--;
  26. if (!pos[m].d) {
  27. que.push(m);
  28. }
  29. }
  30. }
  31. if (fur != n) return 0;//fur为排序中的点的个数,如果有点未加入排序中,说明存在环,即不存在拓扑排序
  32. else return 1;
  33. }
  34. int main() {
  35. cin >> n >> m;
  36. for (int i = 1; i <= m; i++) {//接收图
  37. int a, b; scanf("%d%d", &a, &b);
  38. pos[a].ne.push_back(b); pos[b].d++;
  39. }
  40. if (bfs()) {
  41. for (int i = 0; i < n; i++)
  42. cout << p[i] << ' ';
  43. }
  44. else cout << -1;
  45. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/870685
推荐阅读
相关标签
  

闽ICP备14008679号