CF999E Reachability from the Capital

对于缩点后得到的DAG,我们求出入度为0的强连通分量的个数,即为最少的需要添加的边。(注意判断首都所在的强连通分量的入度)
#include <bits/stdc++.h>
using namespace std;
const int N=5e3+5;
int n,m,s,u[N],v[N],ans,du[N];
int now,top,col,dfn[N],low[N],sta[N],color[N];
int cnt,head[N];
struct edge{int next,to;}e[N<<1];

inline void add(int u,int v)
{
	cnt++;
	e[cnt].next=head[u];
	e[cnt].to=v;
	head[u]=cnt;
}

void tarjan(int u)
{
	dfn[u]=low[u]=++now;
	sta[++top]=u;
	for (register int i=head[u]; i; i=e[i].next)
	if (!dfn[e[i].to])
	{
		tarjan(e[i].to);
		low[u]=min(low[u],low[e[i].to]);
	}
	else if (!color[e[i].to]) low[u]=min(low[u],low[e[i].to]);
	if (dfn[u]==low[u])
	{
		col++;
		while (sta[top]!=u) color[sta[top]]=col,top--;
		color[sta[top]]=col,top--;
	}
}

int main(){
	scanf("%d%d%d",&n,&m,&s);
	for (register int i=1; i<=m; ++i) scanf("%d%d",&u[i],&v[i]),add(u[i],v[i]);
	for (register int i=1; i<=n; ++i) if (!dfn[i]) tarjan(i);
	for (register int i=1; i<=m; ++i) if (color[u[i]]!=color[v[i]]) du[color[v[i]]]++;
	for (register int i=1; i<=col; ++i) if (!du[i] && i!=color[s]) ans++;
	printf("%d\n",ans);
return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值