果断对Tarjan不熟啊,Tarjan后缩点,求树上的最长路,注意重边的处理,借鉴宝哥的做法,开标记数组,标记自己的反向边。
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <cstdlib>
using namespace std;
#define N 200001
#define M 2000001
#define INF 0x3f3f3f3f
struct node
{
int u,v,next;
}edge[M];
struct na
{
int u,v,w,next;
}tree[M];
int first[N],DFN[N],Belong[N],stack[N],Low[N],cnum[N];
int in[N],d[N],fr[N];
int qu[M],qv[M];
int n,m;
bool vis[M];
int tot,scnt,top;
void CL()
{
tot = scnt = top = ;
memset(first,-,sizeof(first));
memset(fr,-,sizeof(fr));
memset(in,,sizeof(in));
memset(DFN,,sizeof(DFN));
memset(vis,,sizeof(vis));
}
void add(int u,int v)
{
edge[tot].u = u;
edge[tot].v = v;
edge[tot].next = first[u];
first[u] = tot ++;
}
void addt(int u,int v)
{
tree[tot].u = u;
tree[tot].v = v;
tree[tot].w = ;
tree[tot].next = fr[u];
fr[u] = tot ++;
}
void Tarjan(int u,int num)
{
int v,i;
DFN[u] = Low[u] = ++ tot;
stack[top++] = u;
in[u] = ;
for(i = first[u];i != -;i = edge[i].next)
{
v = edge[i].v;
if(vis[i]) continue;
vis[i] = vis[i^] = ;
if(!DFN[v])
{
//printf("cc%d %d",v,i);
Tarjan(v,i);
Low[u] = min(Low[u],Low[v]);
}
else if(in[v])
{
Low[u] = min(Low[u],DFN[v]);
}
}
if(DFN[u] == Low[u])
{
scnt ++;
do
{
v = stack[--top];
Belong[v] = scnt;
in[v] = ;
cnum[scnt] ++;
}while(u != v);
}
}
int spfa(int x)
{
int i,key,v,u,minz = ;
for(i = ;i <= scnt;i ++)
{
in[i] = ;
d[i] = INF;
}
queue<int> que;
in[x] = ;
d[x] = ;
que.push(x);
while(!que.empty())
{
u = que.front();
in[u] = ;
que.pop();
for(i = fr[u];i != -;i = tree[i].next)
{
v = tree[i].v;
if(d[v] > d[u] + tree[i].w)
{
d[v] = d[u] + tree[i].w;
if(!in[v])
{
in[v] = ;
que.push(v);
}
}
}
}
for(i = ;i <= scnt;i ++)
{
if(minz < d[i])
{
minz = d[i];
key = i;
}
}
return key;
}
int main()
{ int i,u,v,str,x;
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n == &&m == ) break;
CL();
for(i = ;i <= m;i ++)
{
scanf("%d%d",&u,&v);
if(i == )
str = u;
qu[i] = u;
qv[i] = v;
add(u,v);
add(v,u);
}
tot = ;
Tarjan(u,);
tot = ;
for(i = ;i <= m;i ++)
{
if(Belong[qu[i]] != Belong[qv[i]])
{
addt(Belong[qu[i]],Belong[qv[i]]);
addt(Belong[qv[i]],Belong[qu[i]]);
}
}
if(scnt == )
printf("0\n");
else
{
x = spfa(spfa());
printf("%d\n",scnt-d[x]-);
}
}
return ;
}