HDU-2767 tarjan缩点

Input
On the first line one positive number: the number of testcases, at most 100. After that per testcase:

  • One line containing two integers n (1 ≤ n ≤ 20000) and m (0 ≤ m ≤ 50000): the number of statements and the number of implications that have already been proved.
  • m lines with two integers s1 and s2 (1 ≤ s1, s2 ≤ n and s1 ≠ s2) each, indicating that it has been proved that statement s1 implies statement s2.

Output
Per testcase:

  • One line with the minimum number of additional implications that need to be proved in order to prove that all statements are equivalent.

Sample Input
2
4 0
3 2
1 2
1 3

Sample Output
4
2

求再连几条边让该有向图是一个强连通,
因为强连通没有出入度=0的点,
所以 ans = max(sum(in[i]==0), sum(out[i]==0))
代码

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int N=2e4+5;
int head[N<<2],tot;
struct Edge{
	int from,to,next;
	Edge(){}
	Edge(int from,int to):from(from),to(to){next=head[from];}
}E[N<<2];
inline void addedge(int u,int v){
	E[tot]=Edge(u,v),head[u]=tot++;
}
int low[N],dfn[N],sta[N],scc[N],insta[N];
int id,top,cnt;
void tarjan(int u,int v=0){
	low[sta[++top]=u]=dfn[u]=++id;insta[u]=1;
	for(int i=head[u];~i;i=E[i].next){
		v=E[i].to;
		if(!dfn[v]){
			tarjan(v);
			low[u]=min(low[u],low[v]);
		}else if(insta[v])low[u]=min(low[u],dfn[v]);
	}
	if(low[u]^dfn[u])return;
	++cnt;
	do{
		v=sta[top--];
		scc[v]=cnt;
		insta[v]=0;
	}while(u^v);
}
int n,m,u,v,t,i;
int in[N],out[N];
void init(){
	for(int i=1;i<=n;++i)dfn[i]=in[i]=out[i]=insta[i]=0;
	memset(head,-1,sizeof(head));
	cnt=top=tot=id=0;
}
int main(){
	scanf("%d",&t);
	while(t--){
		scanf("%d%d",&n,&m);
		init();
		while(m--)scanf("%d%d",&u,&v),addedge(u,v);
		for(i=1;i<=n;++i)if(!dfn[i])tarjan(i);
		for(i=0;i<tot;++i){
			u=scc[E[i].from],v=scc[E[i].to];
			if(u^v)++in[v],++out[u];
		}
		for(i=1,u=0,v=0;i<=cnt;++i)u+=!in[i],v+=!out[i];
		printf("%d\n",cnt>1?max(u,v):0);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值