拓扑排序详解(梅开二度之dfs版按字典序输出拓扑路径+dfs版输出全部拓扑路径 (4)

就是一个dfs,每次dfs都让入度为0且没有标记的点 i 去更新其后继节点,然后将 i 放进ans数组中,然后标记一下,去dfs(num + 1),回溯的时候,就把所有更新的点的入度都加回来,把 i 重新标记为0。

#include <cstdio> #include <cstring> #include <string> #include <cmath> #include <iostream> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <stdlib.h> #include <sstream> #include <map> #include <set> using namespace std; #define inf 0x3f3f3f3f #define MAX 200000 + 50 #define endl '\n' #define seed 13331 #define mod 1000000000 + 7 #define io ios::sync_with_stdio(false); cin.tie(0); cout.tie(0) #define mem(a,b) memset((a),(b),sizeof(a)) typedef long long ll ; //不开longlong见祖宗! //inline __int128 read(){__int128 x = 0, f = 1;char ch = getchar();while(ch < '0' || ch > '9'){if(ch == '-'){f = -1;}ch = getchar();}while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}return x * f;} //inline void print(__int128 x){if(x < 0){putchar('-');x = -x;}if(x > 9){print(x / 10);}putchar(x % 10 + '0');} inline int IntRead(){char ch = getchar();int s = 0, w = 1;while(ch < '0' || ch > '9'){if(ch == '-') w = -1;ch = getchar();}while(ch >= '0' && ch <= '9'){s = s * 10 + ch - '0';ch = getchar();}return s * w;} inline void write(int x){if (x < 0) {x = ~x + 1; putchar('-');}if (x > 9){write(x / 10);}putchar(x % 10 + '0');} int n, m, a, b, tot, now; int head[MAX]; int in[MAX]; bool vis[MAX]; struct ran{ int to, next; }tr[MAX]; int ans[MAX]; void init(){ mem(in, 0); mem(vis, 0); mem(tr, 0); mem(head, -1); tot = 0; } void built(int u, int v){ tr[++tot].to = v; tr[tot].next = head[u]; head[u] = tot; } void dfs(int num){ if(num == n + 1){//如果数量到n+1,就输出 for(int i = 1; i <= n; ++i){ cout<<ans[i]<<' '; } cout<<endl; } for(int i = 1; i <= n; ++i){ if(!in[i] && !vis[i]){//入度为0,且没被标记过 int u = i; for(int j = head[u]; j != -1; j = tr[j].next){ --in[tr[j].to];//遍历所有后继节点 } vis[u] = 1;//标记一下点i ans[num] = u;//把他放进ans数组 dfs(num + 1);//继续搜 for(int k = head[u]; k != -1; k = tr[k].next){ ++in[tr[k].to]; }//把入度更新回来 vis[u] = 0;//取消标记 } } return; } int main(){ io; while (cin>>n>>m && (n + m)) { init(); for(int i = 1; i <= m; ++i){ cin>>a>>b; built(a, b); ++in[b]; } dfs(1); } return 0; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zygpyy.html