一,利用dfs进行拓扑排序
#include<iostream>
using namespace std;
/*----------------------------------------------
代码比较乱,大概就是
c[]数组表示状态,-1表示正在dfs,1表示已经dfs完毕,0表示未访问
for (遍历所有节点v){
if(!c[v] && !dfs(v))
return false;
}
------------------------------------------------*/
const int maxn = 100;
int G[maxn][maxn];
int v[maxn];
int tp[maxn];
int t, n;
bool topo(int u) {
v[u] = -1;
for (int i = 1;i <= n;i++) {
if (G[u][i]) {
if (v[i] < 0)
return false;
else if (!v[i] && !topo(i))
return false;
}
}
v[u] = 1;tp[--t] = u;
return true;
}
int main() {
memset(v, 0, sizeof(v));
memset(G, 0, sizeof(G));
int a, b;
cin >> n;
while (cin >> a >> b && a) {
G[a][b] = 1;
}
t = n;
for (int i = 1;i <= n;i++) {
if (!v[i] && !topo(i)) {
cout << "no topo\n";
return 0;
}
}
for (int i = 0;i < n;i++) {
cout << " " << tp[i];
}
}
二、
参考文章:https://blog.csdn.net/qq_41713256/article/details/80805338
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 15;
vector<int>L;
int in[maxn];
int G[maxn][maxn];
int n;
bool topo() {
queue<int> p;//可以用priority_queue;
for (int i = 1;i <= n;i++) {
if (in[i] == 0)
p.push(i);
}
while (!p.empty()) {
int t = p.front();
p.pop();
L.push_back(t);
for (int i = 1;i <= n;i++) {
if (G[t][i]) {
in[i]--;
if (in[i] == 0)
p.push(i);
}
}
}
if (L.size() != n)
return false;
return true;
}
int main() {
memset(G, 0, sizeof(G));
memset(in, 0, sizeof(in));
L.clear();
int a, b;
cin >> n;
while (cin >> a >> b && (a || b)) {
G[a][b] = 1;
in[b]++;
}
if (topo()) {
for (int i = 0;i < L.size();i++) {
cout << " " << L[i];
}
}
}
由于拓扑排序有多种情况 mark一下,打游戏去 了