条件:必须在有向无环图中(DAG)中。
使用dfs来对DAG求出拓扑排序。
例题和代码:
例题:https://vjudge.net/problem/UVA-10305#author=0
代码:
#include <iostream>
#include <cstdio>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <cstring>
#include <cmath>
#include <stack>
#include <queue>
using namespace std;
const int maxn = 110;
int matrix[maxn][maxn];
// 0:未访问 -1:正在访问 1:已访问
int vis[maxn];
int topo[maxn], tt;
// 拓扑dfs
bool dfs(int m, int u) {
vis[u] = -1;
for(int i = 1; i <= m; i++) {
if(matrix[u][i]) {
// 存在有向环
if(vis[i] == -1) return false;
if(!vis[i]) {
bool flag = dfs(m, i);
if(!flag) return false;
}
}
}
vis[u] = 1;
topo[--tt] = u;
return true;
}
int main() {
// freopen("i.txt", "r", stdin);
// freopen("o.txt", "w", stdout);
int m,n;
while(cin >> m >> n) {
if(!n && !m) break;
tt = m;
memset(matrix, 0, sizeof(matrix));
memset(vis, 0, sizeof(vis));
memset(topo, 0, sizeof(topo));
for(int i = 0; i < n; i++) {
int t1, t2;
cin >> t1 >> t2;
matrix[t1][t2] = 1;
}
for(int i = 1; i <= m; i++) {
if(!vis[i]) {
dfs(m, i);
}
}
cout << topo[0];
for(int i = 1; i < m; i++)
cout << " " << topo[i];
cout << endl;
}
return 0;
}
来源:CSDN
作者:1hdmx1t
链接:https://blog.csdn.net/qq_43185391/article/details/104005263