算法:拓扑排序

拓扑排序

定义

将一个有向无环图的所有顶点排成一个线性序列,满足所有单向边都由序号小的顶点指向序号大的顶点,这就是拓扑排序。

思路

计算所有顶点的入度,将入度为 0 0 0的顶点排在前面,即序号较小的位置,然后删去这些顶点以及连接的边,再从剩下的顶点中选取入度为 0 0 0的顶点排序,不断循环直到所有顶点均分配好序号。因为当顶点被分配序号时入度为 0 0 0,即所有指向该顶点的边均来自序号更小的顶点,所以按序号形成的线性序列满足拓扑排序的条件。由于有向图无环,故在循环中不可能出现所有顶点的入度都大于 0 0 0的情况。

时间复杂度

设单向边的数量为 m m m,则时间复杂度为 O ( m ) O(m) O(m)

测试

POJ:2367

模板

#include <iostream>
using namespace std;
#include <cstring>
#include <queue>
#include <vector>

const int N = 2e5+10;  // the maximal number

vector<int> edge[N];  // the directed edge of vertex
int order[N];  // the order of vertex
int indeg[N];  // the indegree of vertex
int n;  // the number of vertex

void TP() {
  // count the indegree
  memset(indeg, 0, sizeof(indeg));
  for (int i = 1; i <= n; ++i) {
    for (int j = 0; j < edge[i].size(); ++j) {
      ++indeg[edge[i][j]];
    }
  }

  queue<int> q;
  for (int i = 1; i <= n; ++i) {
    if (indeg[i] == 0) {
      q.push(i);
    }
  }

  int pos = 1;
  while (!q.empty()) {
    int curr = q.front();
    order[curr] = pos++;  // allocate the order
    q.pop();

    for (int i = 0; i < edge[curr].size(); ++i) {
      --indeg[edge[curr][i]];  // decrease the indegree
      if (indeg[edge[curr][i]] == 0) {
        q.push(edge[curr][i]);
      }
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值