Kahn算法
无前趋的的顶点优先拓扑排序
每次取出入度为0的点,得到拓扑序列
1、先将所有入度为0的点放入一个队列,每次取出一个点放入拓扑序列中,并删除这个点的所有边。
2、如果删除一条边后该点的入度为0,则将该点放入队列,直到队列为空。
3、如果图中存在有向环的话,环上的所有点入度都不为0,所以不会被放入队列。
4、所以最后需要检查拓扑序列中的点数是否等于图中的点数,如果不等于,则说明图中存在有向环,排序失败。如果等于,则说明图中不存在有向环,排序成功。
时间复杂度为 O ( E + V ) O(E+V) O(E+V)
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 2005;
int t, n, m;
int in[N]; // 每个节点的度
queue<int> q;
vector<int> edge[N], topo; // topo为拓扑序列
void init()
{
for (int i = 1; i <= n; i++) {
edge[i].clear();
in[i] = 0;
}
while (!q.empty())
q.pop();
topo.clear();
}
bool toposort()
{
for (<