码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 2553 The Bottom of a Graph(强连通分量)

时间:2014-10-20 19:33:28      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

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(强连通分量)

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://blog.csdn.net/accelerator_/article/details/40304001

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!