CF1000E We Need More Bosses

对无向图进行缩点后求树直径即为答案。
#include <bits/stdc++.h>
using namespace std;
const int N=3e5+5;
int n,m,u[N],v[N],ans,p;
int now,top,col,dfn[N],low[N],sta[N],color[N];
int cnt=1,head[N];
struct edge{int next,to; bool vis;}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 (!e[i].vis)
	{
		e[i].vis=e[i^1].vis=true;
		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--;	
	}
}

void dfs(int u,int fa,int dis)
{
	if (dis>ans) ans=dis,p=u;
	for (register int i=head[u]; i; i=e[i].next) if (e[i].to!=fa) dfs(e[i].to,u,dis+1);	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值