洛谷 P2341 [HAOI2006]受欢迎的牛|【模板】强连通分量 tarjan缩点

题目背景
本题测试数据已修复。

题目描述
每头奶牛都梦想成为牛棚里的明星。被所有奶牛喜欢的奶牛就是一头明星奶牛。所有奶

牛都是自恋狂,每头奶牛总是喜欢自己的。奶牛之间的“喜欢”是可以传递的——如果A喜

欢B,B喜欢C,那么A也喜欢C。牛栏里共有N 头奶牛,给定一些奶牛之间的爱慕关系,请你

算出有多少头奶牛可以当明星。

输入格式
 第一行:两个用空格分开的整数:N和M

 第二行到第M + 1行:每行两个用空格分开的整数:A和B,表示A喜欢B

输出格式
 第一行:单独一个整数,表示明星奶牛的数量

输入输出样例
输入 #1
3 3
1 2
2 1
2 3
输出 #1
1
说明/提示
只有 3 号奶牛可以做明星

【数据范围】

10%的数据N<=20, M<=50

30%的数据N<=1000,M<=20000

70%的数据N<=5000,M<=50000

100%的数据N<=10000,M<=50000

解法:tarjan缩点

  • 由于明星奶牛所有的奶牛都喜欢,那么明星奶牛的出度应该为0,如果有多个奶牛的出度都为0,那么应该输出0,因为这些奶牛不相互喜欢,所以没有明星奶牛

AC代码

#include<cstdio>
#include<stack>
#define si 10005
#define re register int
using namespace std;
struct edge {
	int nex,to;
}e[si*5];
int n,m,cnt,head[si],chu[si];
int num,tot,dfn[si],low[si],a[si],sz[si];
bool v[si]; stack<int> s;
inline int read() {
	int x=0,cf=1;
	char ch=getchar();
	while(ch<'0'||ch>'9') {
		if(ch=='-') cf=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9') {
		x=(x<<3)+(x<<1)+(ch^48);
		ch=getchar();
	}
	return x*cf;
}
inline void add(int x,int y) {
	e[++cnt].to=y,e[cnt].nex=head[x],head[x]=cnt;
}
inline void tarjan(int x) {
	dfn[x]=low[x]=++num;
	s.push(x),v[x]=true;
	for(re i=head[x];i;i=e[i].nex) {
		int y=e[i].to;
		if(!dfn[y]) tarjan(y),low[x]=min(low[x],low[y]);
		else if(v[y]) low[x]=min(low[x],dfn[y]);
	}
	if(dfn[x]==low[x]) {
		tot++;
		while(x!=s.top()) {
			a[s.top()]=tot; sz[tot]++;
			v[s.top()]=false; s.pop();
		}
		a[s.top()]=tot; sz[tot]++;
		v[s.top()]=false; s.pop();
	}
	return;
}
int main() {
	n=read(),m=read();
	for(re i=1;i<=m;i++) {
		int x=read(),y=read();
		add(x,y);
	}
	for(re i=1;i<=n;i++) {
		if(!dfn[i]) tarjan(i);
	}
	for(re i=1;i<=n;i++) {
		for(re j=head[i];j;j=e[j].nex) {
			if(a[i]!=a[e[j].to]) chu[a[i]]++;
		}
	}
	int ans=0;
	for(re i=1;i<=tot;i++) {
		if(!chu[i]) {
			if(ans) {
				printf("0");
				return 0;
			}
			ans=i;
		}
	}
	printf("%d",sz[ans]);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章