首页 > 代码库 > POJ 2553 The Bottom of a Graph(强连通分量)
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; }
POJ 2553 The Bottom of a Graph(强连通分量)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。