拓扑排序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\n"); else printf("Wrong\n"); } 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\n"); else printf("Wrong\n"); } return 0; }