[HAOI2006]受欢迎的牛,洛谷之提高历练地,强连通分量

正题

      [HAOI2006]受欢迎的牛

      其实这道题就是求缩点之后,入度为0的环的大小。

      我们跑一便Tarjan缩点之后,记录每个点所在环的编号和大小即可。

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

int n,m;
int first[10010];
struct edge{
	int x,y,next;
}s[100010];
struct node{
	int dfn,low;
}op[10010];
int len=0;
bool we[10010];
bool tf[10010];
int where[10010];
int diss[10010];
int node=0;
int tot=0,now=0;
vector<int> T[10010];
stack<int> f;

void ins(int x,int y){
	len++;
	s[len].x=x;s[len].y=y;s[len].next=first[x];first[x]=len;
}

void Tarjan(int x){
	tf[x]=true;f.push(x);
	op[x].dfn=op[x].low=++now;
	for(int i=first[x];i!=0;i=s[i].next){
		int y=s[i].y;
		if(op[y].dfn==0){
			Tarjan(y);
			if(op[y].low<op[x].low) op[x].low=op[y].low;
		}
		else if(tf[y])
			if(op[y].dfn<op[x].low) op[x].low=op[y].dfn;
	}
	if(op[x].dfn==op[x].low){
		tot++;
		while(1){
			int k=f.top();
			f.pop();
			T[tot].push_back(k);
			where[k]=tot;
			tf[k]=false;
			if(k==x) break;
		}
	}
}

int main(){
	scanf("%d %d",&n,&m);
	for(int i=1;i<=m;i++){
		int x,y;
		scanf("%d %d",&x,&y);
		ins(x,y);
	}
	for(int i=1;i<=n;i++)
		if(op[i].dfn==0) Tarjan(i);
	for(int i=1;i<=m;i++){
		int x=s[i].x,y=s[i].y;
		if(where[x]!=where[y])
			diss[where[x]]++;
	}
	int ans=0;
	for(int i=1;i<=tot;i++){
		if(diss[i]==0){
			if(ans==0) ans=T[i].size();
			else {
				printf("0");
				return 0;	
			}	
		}
	}
	printf("%d\n",ans);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值