【tarjan】P2746 [USACO5.3]校园网Network of Schools

 

首先就是tarjan缩点,在一个强连通块内的有一个能收到信息就可以将信息传递给所有点

然后统计一下入度出度,任务A就是求入度为0的联通块的个数,任务B是入度和出度为0的连通块的个数的最大值

 

注意特判:全部在一个连通块的时候要特判!!

 

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn=10005;
int n,cnt,top,in[105],out[105],head[105],st[105],inin[105],xx[maxn],y[maxn],tot,dfn[105],low[105],col[105],times,col_type;
struct edge
{
	int to,nxt;
}G[maxn];
void add(int x,int y)
{
	G[++cnt].to=y; G[cnt].nxt=head[x]; head[x]=cnt;
}
void tarjan(int x)
{
	low[x]=dfn[x]=++times;
	st[++top]=x; inin[x]=1;
	for(int i=head[x];i;i=G[i].nxt)
	{
		int to=G[i].to;
		if(!dfn[to])
		{
			tarjan(to);
			low[x]=min(low[x],low[to]);
		}
		else if(inin[to]) low[x]=min(low[x],dfn[to]);
	}
	if(dfn[x]==low[x])
	{
		col_type++;
		while(st[top+1]!=x)
		{
			col[st[top]]=col_type;
			inin[st[top--]]=0;
		}
	}
}
int main()
{
	freopen("a.in","r",stdin);
	scanf("%d",&n);
	int x;
	for(int i=1;i<=n;i++)
		while(scanf("%d",&x) && x!=0)
		{
			xx[++tot]=i; y[tot]=x; 
			add(i,x);
		}
	for(int i=1;i<=n;i++) if(!dfn[i]) tarjan(i);
	if(col_type==1)
	{
		printf("%d\n%d",1,0);
		return 0;
	}
	for(int i=1;i<=tot;i++)
		if(col[xx[i]]!=col[y[i]])
			out[col[xx[i]]]++,in[col[y[i]]]++;
	int ans1=0;
	for(int i=1;i<=col_type;i++)
		if(!in[i]) ans1++;
	int ans2=0;
	for(int i=1;i<=col_type;i++)
		if(!out[i]) ans2++;
	printf("%d\n%d",ans1,max(ans1,ans2));
	return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值