首先求出整个图的强连通分量,就各个强连通分量缩为一个点,得到一棵树。那么当天树 的节点减一就是当前桥的数量,而求的是加一条边之后桥的最小数量。也就是说加的这一条边的两个端点到他们lca的路径上经过的点要最多,其实就是求树上的最长链。
求最长链的算法
从任意一个点出发,找到离他最远的一个点u;
然后在从这个点u出发,找到离他最远的一个点v
则u-v就是最长链。
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <stack>
#include <vector>
#include <string.h>
#include <queue>
#define msc(X) memset(X,-1,sizeof(X))
#define ms(X) memset(X,0,sizeof(X))
typedef long long LL;
using namespace std;
const int MAXN=200010;
const int MAXM=2000010;
struct _Edge
{
int to,next;
bool cut;
}edge[MAXM];
int hd[MAXN],tot;
int Low[MAXN],DFN[MAXN],Stack[MAXN],Belong[MAXN];
int Index,top;
int block;
bool Instack[MAXN];
int bridge;
void addedge(int u,int v)
{
edge[tot].to=v;
edge[tot].next=hd[u];
edge[tot].cut=false;
hd[u]=tot++;
}
void Tarjan(int u,int pre)
{
int v;
Low[u]=DFN[u]=++Index;
Stack[top++]=u;
Instack[u]=true;
int pre_cnt=0;
for(int i=hd[u];i!=-1;i=edge[i].next)
{
v=edge[i].to;
if(v==pre&&pre_cnt==0) {pre_cnt++;continue;}
if(!DFN[v]){
Tarjan(v,u);
if(Low[u]>Low[v]) Low[u]=Low[v];
if(Low[v]>DFN[u]){
bridge++;
edge[i].cut=true;
edge[i^1].cut=true;
}
}
else if(Instack[v]&&Low[u]>DFN[v])
Low[u]=DFN[v];
}
if(Low[u]==DFN[u]){
block++;
do{
v=Stack[--top];
Instack[v]=false;
Belong[v]=block;
}while(v!=u);
}
}
void inti(void)
{
ms(Instack);
ms(DFN);
ms(Belong);
Index=top=block=bridge=tot=0;
msc(hd);
}
int deg[MAXN];
vector<int> son[MAXN];
int bfs(int root)
{
int ret=root;
msc(deg);
deg[root]=0;
queue<int > que;
que.push(root);
while(!que.empty())
{
int tmp=que.front();
que.pop();
int sz=son[tmp].size();
for(int i=0;i<sz;i++)
{
int v=son[tmp][i];
if(deg[v]!=-1) continue;
deg[v]=deg[tmp]+1;
if(deg[v]>deg[ret])
ret=v;
que.push(v);
}
}
return ret;
}
int main(int argc, char const *argv[])
{
int n,m;
while(scanf("%d %d",&n,&m)==2&&(n||m))
{
inti();
while(m--){
int a,b,tmp=0;
scanf("%d %d",&a,&b);
/*char ch;
while(ch=getchar(),ch<'0'||ch>'9') continue;
tmp=ch-'0';
while(ch=getchar(),'0'<=ch&&ch<='9')
tmp=10*tmp+ch-'0';
a=tmp;
while(ch=getchar(),ch<'0'||ch>'9') continue;
tmp=ch-'0';
while(ch=getchar(),'0'<=ch&&ch<='9')
tmp=10*tmp+ch-'0';
b=tmp;*/
addedge(a,b);
addedge(b,a);
}
Tarjan(1,-1);
if(block<=3) {puts("0");continue;}
//缩点
int ans=block-1;
for(int i=1;i<=block;i++)
son[i].clear();
for(int u=1;u<=n;u++)
for(int i=hd[u];i!=-1;i=edge[i].next)
if(edge[i].cut)
{
son[Belong[u]].push_back(Belong[edge[i].to]);
son[Belong[edge[i].to]].push_back(Belong[u]);
}
printf("%d\n",ans-deg[bfs(bfs(1))] );
}
return 0;
}
/*
4 4
1 2
1 3
1 4
2 3
0 0
4 3
1 2
3 2
1 4
0 0
*/