// 逆拓扑排序DFS实现.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <queue>
#include<stack>
#include <cstring> // for memset
#define Max 503
#define INF 0xcffff
using namespace std;
typedef struct AMGraph {
int vex, arc;
int arcs[Max][Max];
} AMGraph;
bool visited[Max];
stack<int>zhan;
queue<int>q;
int firstnode(AMGraph& G, int x) {
for (int i = 1; i <= G.vex; i++) {
if (G.arcs[x][i] > 0 && !visited[i])
return i;
}
return -1;
}
int nextnode(AMGraph& G, int x, int next) {
for (int i = next + 1; i <= G.vex; i++) {
if (G.arcs[x][i] > 0 && !visited[i])
return i;
}
return -1;
}
void DFS(AMGraph& G, int x) {
visited[x] = true;
for (int w = firstnode(G, x); w >= 0; w = nextnode(G, x, w))
if (!visited[w])
DFS(G, w);
zhan.push(x);
q.push(x);
/*cout << x << " ";*/
}
void DFSTraverse(AMGraph& G) {
for (int i : visited)
visited[i] = false;
int count = 0;
for (int i = 1; i <= G.vex; i++) {
if (!visited[i]) {
cout <<"入点" << i << " "<<endl;
DFS(G, i);
count++;
}
}
cout << "\n连通分量数为:" << count << endl;
}
void putin(AMGraph& G) {
int u, v;
cin >> G.vex >> G.arc;
for (int i = 1; i <= G.vex; i++) {
for (int j = 1; j <= G.vex; j++) {
if (i == j) G.arcs[i][j] = 0;
else G.arcs[i][j] = -1; // 初始化为-1,表示无边
}
}
for (int i = 0; i < G.arc; i++) {
cin >> u >> v;
G.arcs[u][v] = 1;
}
}
int main() {
AMGraph G;
putin(G);
DFSTraverse(G);
cout << "拓扑排序是:";
while (!zhan.empty()) {
cout << zhan.top() << " ";
zhan.pop();
}
cout << "\n逆拓扑排序是:";
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
return 0;
}
/*
5 7
2 5
2 4
2 1
3 1
5 3
4 5
4 3
*/
08-09
118
02-21
1万+
03-18
1413