模板总结归纳:
//拓扑排序
//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;
}