对无向图进行缩点后求树直径即为答案。
#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;
}