拓扑排序
定义
将一个有向无环图的所有顶点排成一个线性序列,满足所有单向边都由序号小的顶点指向序号大的顶点,这就是拓扑排序。
思路
计算所有顶点的入度,将入度为 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]);
}
}
}
}