E. We Need More Bosses(无向图环缩点+树的直径)

题目

题意:

    给定一张无向图,要求在上面选择两个点s,t,若某条边删去后,无法从s到t,则对答案的贡献加1,要求最大的答案。
     2 ≤ n ≤ 3 ⋅ 1 0 5 , n − 1 ≤ m ≤ 3 ⋅ 1 0 5 。 2≤n≤3⋅10^5 , n−1≤m≤3⋅10^5。 2n3105,n1m3105

分析:

    首先成环的那些边一定不会对答案产生贡献,所以我们把成环的点缩成一个点,然后缩点之后,图就无环了,也就变成了一棵树。那么答案就是树的直径了。

#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;

vector<int> g[300005],g_new[300005];
int vis[300005],dfn[300005],low[300005];
int scc[300005],c = 1;   
stack<int> s;
int cnt = 0;  
int depth[300005];

void tarjan(int x,int fa)    
{
	dfn[x] = low[x] = ++cnt;
	s.push(x);
	vis[x] = 1;
	for (int i = 0; i < g[x].size(); i++)
	{
		int t = g[x][i];
		if( t == fa ) continue;
		if( !dfn[t] )   
		{
			tarjan(t,x);
			low[x] = min(low[x],low[t]); 
		}else if( vis[t] )   
		{
			low[x] = min(low[x],low[t]);   
		}
	} 
	if( dfn[x] == low[x] )    
	{
		vis[x] = 0;
		scc[x] = c;        
		while( s.top() != x )   
		{
			vis[s.top()] = 0;
			scc[s.top()] = c;  
			s.pop(); 
		}
		c ++;  
		s.pop();   
	}
}

void compress(int n)  
{
	for (int i = 1; i <= n; i++)
	{
		for (int j = 0; j < g[i].size(); j++)  
		{
			int t = g[i][j];
			if( scc[i] != scc[t] ) 
			{
				g_new[scc[i]].push_back(scc[t]);   
			}
		}
	}
}

void dfs(int x,int fa)
{
	depth[x] = depth[fa] + 1;
	for (int i = 0; i < g_new[x].size(); i++)
	{
		int t = g_new[x][i];
		if( t == fa ) continue;
		dfs(t,x);
	}
}

int main()
{
	int n,m;
	cin >> n >> m;
	for (int i = 0; i < m; i++)
	{
		int x,y;
		cin >> x >> y;
		g[x].push_back(y); 
		g[y].push_back(x);
	}
	tarjan(1,0);
	compress(n);
	dfs(1,0);
	int index = 0,maxn = 0;
	for (int i = 1; i <= n; i++)
	{
		if( maxn < depth[i] )
		{
			maxn = depth[i];
			index = i;
		}
	}
	dfs(index,0);
	int ans = 0;
	for (int i = 1; i <= n; i++)
	{
		ans = max(ans,depth[i]);
	}
	cout << ans - 1 << '\n';
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值