模板总结归纳:
//拓扑排序
//O(|V| + |E|)
const int maxn = 1e5+5;
vector <int> g[maxn];
int du[maxn], n, m, L[maxn]; // L储存拓扑排序结果
bool topsort(){
memset(du, 0, sizeof(du));
for(int i = 0; i < n; i++)
for(int j = 0; j < g[i].size(); j++)
du[g[i][j]]++;
int tot = 0;
queue <int> Q;
for(int i = 0; i < n; i++)
if(!du[i]) Q.push(i);
while(!Q.empty()){
int x = Q.front(); Q.pop();
L[tot++] = x;
for(int j = 0; j < g[x].size(); j++){
int t = g[x][j];
du[t]--;
if(!du[t]) Q.push(t);
}
}
if(tot == n) return 1;
return 0;
}实战模板题 :HDU 3342 Legal or Not#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<cstring>
using namespace std;
const int maxn = 110;
vector <int> g[maxn];
int du[maxn], n, m, L[maxn];
bool topsort(){
memset(du, 0, sizeof(du));
for(int i = 0; i < n; i++)
for(int j = 0; j < g[i].size(); j++)
du[g[i][j]]++;
int tot = 0;
queue <int> Q;
for(int i = 0; i < n; i++)
if(!du[i]) Q.push(i);
while(!Q.empty()){
int x = Q.front(); Q.pop();
L[tot++] = x;
for(int j = 0; j < g[x].size(); j++){
int t = g[x][j];
du[t]--;
if(!du[t]) Q.push(t);
}
}
if(tot == n) return 1;
return 0;
}
int main()
{
while(cin >> n >> m)
{
if(n == 0 && m == 0) break;
int a, b;
for(int i = 0; i < n; i++) g[i].clear();
while(m--)
{
cin >> a >> b;
g[a].push_back(b);
}
if(topsort()) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
本文提供了一种高效的拓扑排序算法实现模板,并通过一道实战题目进行应用演示。该算法适用于有向无环图(DAG),能在线性时间内完成排序,帮助判断图中是否存在合法的排序顺序。
&spm=1001.2101.3001.5002&articleId=80101851&d=1&t=3&u=072b0020b1684d09ab5af518651fcd45)
310

被折叠的 条评论
为什么被折叠?



