POJ 1236 Network of Schools(强连通分量)

POJ 1236 Network of Schools

题目链接

题意:题意本质上就是,给定一个有向图,问两个问题
1、从哪几个顶点出发,能走全所有点
2、最少连几条边,使得图强连通

思路:

#include <cstdio>
#include <cstring>
#include <vector>
#include <stack>
using namespace std;

const int N = 105;

int n;
vector<int> g[N];

int pre[N], sccno[N], dfn[N], dfs_clock, sccn;
stack<int> S;

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++;
		while (1) {
			int x = S.top(); S.pop();
			sccno[x] = sccn;
			if (x == u) break;
		}
	}
}

void find_scc() {
	sccn = dfs_clock = 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 in[N], out[N];

int main() {
	while (~scanf("%d", &n)) {
		int v;
		for (int i = 1; i <= n; i++) g[i].clear();
		int cnt = n;
		for (int u = 1; u <= n; u++) {
			while (~scanf("%d", &v) && v)
				g[u].push_back(v);
		}
		find_scc();
		memset(in, 0, sizeof(in));
		memset(out, 0, sizeof(out));
		for (int u = 1; u <= n; u++) {
			for (int j = 0; j < g[u].size(); j++) {
				int v = g[u][j];
				if (sccno[u] != sccno[v]) {
					in[sccno[v]]++;
					out[sccno[u]]++;
				}
			}
		}
		int ins = 0, outs = 0;
		for (int i = 1; i <= sccn; i++) {
			if (!in[i]) ins++;
			if (!out[i]) outs++;
		}
		int ans1 = ins, ans2 = max(ins, outs);
		if (sccn == 1) ans2 = 0;
		printf("%d\n%d\n", ans1, ans2);
	}
	return 0;
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。