Warm up

Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 10532 Accepted Submission(s): 2432

Problem Description
  N planets are connected by M bidirectional channels that allow instant transportation. It’s always possible to travel between any two planets through these channels.
  If we can isolate some planets from others by breaking only one channel , the channel is called a bridge of the transportation system.
People don’t like to be isolated. So they ask what’s the minimal number of bridges they can have if they decide to build a new channel.
  Note that there could be more than one channel between two planets.

Input
  The input contains multiple cases.
  Each case starts with two positive integers N and M , indicating the number of planets and the number of channels.
  (2<=N<=200000, 1<=M<=1000000)
  Next M lines each contains two positive integers A and B, indicating a channel between planet A and B in the system. Planets are numbered by 1…N.
  A line with two integers ‘0’ terminates the input.

Output
  For each case, output the minimal number of bridges after building a new channel in a line.

Sample Input
4 4
1 2
1 3
1 4
2 3
0 0

Sample Output
0

Author
SYSU

Source
2013 Multi-University Training Contest 2


题目大意:我们可以加一条边,问加边之后的桥数目最少为多少。

很明显,我们先 边双连通分量 缩点,之后会形成一棵树,树上的边就是原图的桥。

那么连边的时候,肯定连直径可以消除最多的桥,再bfs求直径即可。


AC代码:

#pragma GCC optimize(2)
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=2e5+10,M=1e6+10;
int n,m,x[M],y[M],vis[N],s,d[N];
int dfn[N],low[N],col[N],brige[M<<1],cnt,co;
int head[N],nex[M<<1],to[M<<1],tot;
stack<int> st;
inline void ade(int a,int b){to[++tot]=b; nex[tot]=head[a]; head[a]=tot;}
inline void add(int a,int b){ade(a,b);	ade(b,a);}
inline void init(){
	cnt=co=0;	tot=1;
	for(int i=1;i<=n;i++)	dfn[i]=low[i]=col[i]=head[i]=0;
	memset(brige,0,sizeof brige);
}
void Tarjan(int x){
	dfn[x]=low[x]=++cnt; vis[x]=1;	st.push(x);
	for(int i=head[x];i;i=nex[i]){
		if(brige[i])	continue;	brige[i]=brige[i^1]=1;
		if(!dfn[to[i]]){
			Tarjan(to[i]);	low[x]=min(low[x],low[to[i]]);
		}else if(vis[to[i]]) low[x]=min(low[x],dfn[to[i]]);
	}
	if(dfn[x]==low[x]){
		int u; co++;
		do{
			u=st.top(); st.pop(); vis[u]=0; col[u]=co;
		}while(u!=x);
	}
}
inline int bfs(int s){
	queue<int> q;	q.push(s);	memset(d,-1,sizeof d); d[s]=0; int id=s;
	while(q.size()){
		int u=q.front();	q.pop();
		for(int i=head[u];i;i=nex[i]){
			if(d[to[i]]==-1){
				d[to[i]]=d[u]+1;	q.push(to[i]);
				if(d[to[i]]>d[id]) id=to[i];
			}
		}
	}
	return id;
}
signed main(){
	while(~scanf("%d %d",&n,&m),n+m){
		init();
		for(int i=1;i<=m;i++)	scanf("%d %d",&x[i],&y[i]),add(x[i],y[i]);
		for(int i=1;i<=n;i++)	if(!dfn[i])	Tarjan(i);
		tot=0;	memset(head,0,sizeof head);
		for(int i=1;i<=m;i++)	if(col[x[i]]!=col[y[i]]) add(col[x[i]],col[y[i]]);
		s=bfs(1);
		printf("%d\n",co-1-d[bfs(s)]);
	}
	return 0;
}