之前很多很多紫书上的东西我都忘了……
抄题解的后果……
做了一下裸题
https://vjudge.net/problem/UVA-10305
拓扑排序还可以来判环
#include<bits/stdc++.h> #define REP(i, a, b) for(register int i = (a); i < (b); i++) #define _for(i, a, b) for(register int i = (a); i <= (b); i++) using namespace std; const int MAXN = 1e3 + 10; struct Edge{ int to, next; }; Edge e[MAXN << 1]; int head[MAXN], ans[MAXN], tot; int vis[MAXN], n, m, t; void AddEdge(int from, int to) { e[tot] = Edge{to, head[from]}; head[from] = tot++; } bool dfs(int u) { vis[u] = -1; for(int i = head[u]; ~i; i = e[i].next) { int v = e[i].to; if(vis[v] == -1) return false; if(!vis[v] && !dfs(v)) return false; } vis[u] = 1; ans[--t] = u; return true; } bool toopsort() { memset(vis, 0, sizeof(vis)); t = n + 1; _for(i, 1, n) if(!vis[i] && !dfs(i)) return false; return true; } int main() { while(~scanf("%d%d", &n, &m) && n) { memset(head, -1, sizeof(head)); tot = 0; _for(i, 1, m) { int u, v; scanf("%d%d", &u, &v); AddEdge(u, v); } if(toopsort()) { _for(i, 1, n - 1) printf("%d ", ans[i]); printf("%d ", ans[n]); } else puts("NO"); } return 0; }
用bfs貌似更好写
#include<bits/stdc++.h> #define REP(i, a, b) for(register int i = (a); i < (b); i++) #define _for(i, a, b) for(register int i = (a); i <= (b); i++) using namespace std; const int MAXN = 1e3 + 10; struct Edge{ int to, next; }; Edge e[MAXN << 1]; int head[MAXN], ans[MAXN], tot; int d[MAXN], n, m, t, cnt; void AddEdge(int from, int to) { e[tot] = Edge{to, head[from]}; head[from] = tot++; } bool toopsort() { queue<int> q; _for(i, 1, n) if(!d[i]) q.push(i); while(!q.empty()) { int u = q.front(); q.pop(); ans[++cnt] = u; for(int i = head[u]; ~i; i = e[i].next) { int v = e[i].to; d[v]--; if(!d[v]) q.push(v); } } return cnt == n; } int main() { while(~scanf("%d%d", &n, &m) && n) { memset(head, -1, sizeof(head)); tot = 0; memset(d, 0, sizeof(d)); _for(i, 1, m) { int u, v; scanf("%d%d", &u, &v); AddEdge(u, v); d[v]++; } cnt = 0; if(toopsort()) { _for(i, 1, n - 1) printf("%d ", ans[i]); printf("%d ", ans[n]); } else puts("NO"); } return 0; }