codeforces 999 E. Reachability from the Capital(强连通tarjan)

本文详细解析了Codeforces 999/E题目的解题思路,通过Tarjan算法求解强连通分量,实现从指定起点到达所有点的最少边数添加策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:
http://codeforces.com/contest/999/problem/E

题意:n个点,m条有向边,起点s,问至少加多少条边,使s能到达所有点

思路:先用tarjan求出强连通分量,因为要求从s能到所有的点,那么s到每个强连通分量至少应该有一条边,所以我们只需要把缩点之后除s点以为所有入度为0的强连通分量添加一条边即可

#include<bits/stdc++.h>
#define fi first
#define se second
#define log2(a) log(n)/log(2)
#define show(a) cout<<a<<endl;
#define show2(a,b) cout<<a<<" "<<b<<endl;
#define show3(a,b,c) cout<<a<<" "<<b<<" "<<c<<endl;
using namespace std;

typedef long long ll;
typedef pair<int, int> P;
typedef pair<P, int> LP;
const ll inf = 1e18 + 10;
const int N = 1e6 + 10;
const ll mod = 1e9+7;
const int base=131;
const double pi=acos(-1);
map<string, int>ml;


map<ll,ll> mp;
map<int,int> vi;




ll b[N], vis[N],dep[N],num[N],a[N] ,n, m,  k,x,y;
ll ex, ey, cnt, ans, sum, flag;
ll in[N];
//vector<int> v[N];
vector<ll> v[N];
map<ll,ll> dp[N];
int dfn[N],low[N],colnum,color[N],top,st[N];

void tarjan(int x)
{
	low[x]=dfn[x]=++cnt;
	vis[x]=1;
	st[++top]=x;
	for(int to:v[x])
	{
		if(!dfn[to])
		{
			tarjan(to);
			low[x]=min(low[x],low[to]);
		}
		else if(vis[to]) low[x]=min(low[x],dfn[to]);
	}
	if(low[x]==dfn[x])
	{
		vis[x]=0;
		color[x]=++colnum;
		while(st[top]!=x)
		{
			color[st[top]]=colnum;
			vis[st[top--]]=0;
		}
		top--;
	}
}



int main( )
{
	ios::sync_with_stdio(false);
	cin.tie(0);

	int s;
	cin>>n>>m>>s;
	for(int i=1;i<=m;i++)
	{
		cin>>a[i]>>b[i];
		v[a[i]].push_back(b[i]);
	}
	for(int i=1;i<=n;i++)
	{
		if(!dfn[i]) tarjan(i);
	}
	for(int i=1;i<=m;i++)
	{
		if(color[a[i]]!=color[b[i]])
		{
			in[color[b[i]]]++;
		}
	}
	for(int i=1;i<=colnum;i++)
	{
		if(!in[i]&&i!=color[s]) ans++;
	}
	cout<<ans;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值