POJ 2553 The Bottom of a Graph(强连通分量)
POJ 2553 The Bottom of a Graph
题意:给定一个有向图,求出度为0的强连通分量
思路:缩点搞就可以
代码:
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <stack> using namespace std; const int N = 5005; int n, m; vector<int> g[N], save[N]; stack<int> S; int pre[N], dfn[N], dfs_clock, sccno[N], sccn; void dfs_scc(int u) { pre[u] = dfn[u] = ++dfs_clock; S.push(u); for (int i = 0; i < g[u].size(); i++) { int v = g[u][i]; if (!pre[v]) { dfs_scc(v); dfn[u] = min(dfn[u], dfn[v]); } else if (!sccno[v]) dfn[u] = min(dfn[u], pre[v]); } if (dfn[u] == pre[u]) { sccn++; save[sccn].clear(); while (1) { int x = S.top(); S.pop(); save[sccn].push_back(x); sccno[x] = sccn; if (x == u) break; } } } void find_scc() { dfs_clock = sccn = 0; memset(pre, 0, sizeof(pre)); memset(sccno, 0, sizeof(sccno)); for (int i = 1; i <= n; i++) if (!pre[i]) dfs_scc(i); } int out[N]; int ans[N], an; int main() { while (~scanf("%d", &n) && n) { for (int i = 1; i <= n; i++) g[i].clear(); scanf("%d", &m); int u, v; while (m--) { scanf("%d%d", &u, &v); g[u].push_back(v); } find_scc(); memset(out, 0, sizeof(out)); for (int i = 1; i <= n; i++) { for (int j = 0; j < g[i].size(); j++) { int v = g[i][j]; if (sccno[i] != sccno[v]) { out[sccno[i]]++; } } } an = 0; for (int i = 1; i <= sccn; i++) { if (!out[i]) { for (int j = 0; j < save[i].size(); j++) ans[an++] = save[i][j]; } } sort(ans, ans + an); for (int i = 0; i < an; i++) printf("%d%c", ans[i], i == an - 1 ? '\n' : ' '); } return 0; }