洛谷 [P2341] 受欢迎的牛

强连通分量

一个结论: 在有向图中, 一个联通块能被所有点遍历当且仅当图中只有一个连通块出度为零

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <stack>
using namespace std;
const int MAXN = 100005;
int init() {
	int rv = 0, fh = 1;
	char c = getchar();
	while(c < '0' || c > '9') {
		if(c == '-') fh = -1;
		c = getchar();
	}
	while(c >= '0' && c <= '9') {
		rv = (rv<<1) + (rv<<3) + c - '0';
		c = getchar();
	}
	return fh * rv;
}
int n, m, nume, head[MAXN], dfn[MAXN], low[MAXN], ind, cnt, fa[MAXN], num[MAXN], out[MAXN], ans;
bool f[MAXN];
struct edge{
	int to, nxt;
}e[MAXN];
void adde(int from, int to) {
	e[++nume].to = to;
	e[nume].nxt = head[from];
	head[from] = nume;
}
stack <int> sta;
void tarjan(int u) {
	low[u] = dfn[u] = ++ind;
	f[u] = 1;
	sta.push(u);
	for(int i = head[u]; i; i = e[i].nxt) {
		int v = e[i].to;
		if(!dfn[v]) {
			tarjan(v);
			low[u] = min(low[u], low[v]);
		}else if(f[v]) low[u] = min(low[u], dfn[v]);
	}
	if(dfn[u] == low[u]) {
		int v;
		cnt++;
		do {
			v = sta.top();
			fa[v] = cnt;
			f[v] = 0;
			num[cnt]++;
			sta.pop();
		} while(v != u);
	}
}
int main() {
	n = init(); m = init();
	for(int i = 1; i <= m; i++) {
		int u = init(), v = init();
		adde(u, v);
	}
	for(int i = 1; i <= n; i++) {
		if(!dfn[i]) tarjan(i);
	}
	for(int i = 1; i <= n; i++) {
		for(int j = head[i]; j; j = e[j].nxt) {
			int v = e[j].to;
			if(fa[i] != fa[v]) out[fa[i]]++;
		}
	}
	for(int i = 1; i <= cnt; i++) {
		if(!out[i]) {
			if(ans) {ans = 0;break;}
			ans = num[i];
		}
	}
	cout << ans << endl;
	return 0;
}
posted @ 2018-05-24 16:23  Mr_Wolfram  阅读(74)  评论(0编辑  收藏