拓扑排序bfs_dfs
Posted cgjh
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了拓扑排序bfs_dfs相关的知识,希望对你有一定的参考价值。
dfs
#include <cstdio> #include <cstring> using namespace std; const int maxn = 1e5+50; struct Edge{ int lst; int to; }edge[maxn*5]; int head[maxn]; int qsz; inline void add(int u, int v) { edge[qsz].lst = head[u]; edge[qsz].to = v; head[u] = qsz++; } int vis[maxn]; int ans[maxn]; int qtot; bool dfs(int u) { int v, i; vis[u] = -1; for (i=head[u]; i; i=edge[i].lst) { v = edge[i].to; if (vis[v] == -1) return false; else if (!vis[v] && !dfs(v)) return false; } ans[qtot--] = u; vis[u] = 1; return true; } int main() { int t, n, m, i, j, u, v; scanf("%d", &t); while (t--) { // init; qsz = 1; memset(head, 0, sizeof(head)); memset( vis, 0, sizeof( vis)); scanf("%d%d", &n, &m); qtot = n; for (i=1; i<=m; ++i) { scanf("%d%d", &u, &v); add(v, u); } for (i=1; i<=n; ++i) if (!vis[i]) if (!dfs(i)) break; if (!qtot) printf("Correct "); else printf("Wrong "); } return 0; }
bfs
#include <cstdio> #include <cstring> using namespace std; const int maxn = 1e5+50; struct Edge{ int lst; int to; }edge[maxn*5]; int head[maxn]; int qsz; int inq[maxn]; int q[maxn]; int qhead; inline void add(int u, int v) { edge[qsz].lst = head[u]; edge[qsz].to = v; head[u] = qsz++; } int main() { int t, n, m, i, j, u, v; scanf("%d", &t); while (t--) { // init; qsz = 1; memset(head, 0, sizeof(head)); memset(inq, 0, sizeof( inq)); qhead = 0; scanf("%d%d", &n, &m); for (i=1; i<=m; ++i) { scanf("%d%d", &u, &v); add(u, v); inq[v]++; } for (i=1; i<=n; ++i) if (!inq[i]) q[qhead++] = i; for (i=0; i<qhead; ++i) { for (j=head[q[i]]; j; j=edge[j].lst) { v = edge[j].to; inq[v]--; if (!inq[v]) q[qhead++] = v; } } if (qhead == n) printf("Correct "); else printf("Wrong "); } return 0; }
以上是关于拓扑排序bfs_dfs的主要内容,如果未能解决你的问题,请参考以下文章