HDU 4612 Warm up

来源:互联网 发布:ubuntu pyqt 安装 编辑:程序博客网 时间:2024/05/16 19:54
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 41 21 31 42 30 0
 

Sample Output
0
题目大意:给定一张无向图(有重边),求增加一条边之后的最少桥数。
先tarjan缩点,原图变成一棵树,求树上直径,即为最多减少的桥数。
特判:如果原图没有桥,直接输出0.

#include<iostream>#include<cstring>#include<cstdio>#include<stack>using namespace std;const int N=200005;const int M=1000005;int n,m,cnt,dcnt,tim,pos,mx,hd[N],x[M],y[M],dfn[N],low[N],belong[N],dis[N];stack<int>stk;struct edge{int to,nxt;}v[2*M];void addedge(int x,int y){v[++cnt].to=y;v[cnt].nxt=hd[x];hd[x]=cnt;}void tarjan(int u,int fa){bool flg=0;dfn[u]=low[u]=++tim;stk.push(u);for(int i=hd[u];i;i=v[i].nxt)if(!dfn[v[i].to]){tarjan(v[i].to,u);low[u]=min(low[u],low[v[i].to]);}else if(v[i].to==fa&&!flg)flg=1;elselow[u]=min(low[u],dfn[v[i].to]);if(dfn[u]==low[u]){dcnt++;while(1){int t=stk.top();stk.pop();belong[t]=dcnt;if(u==t)break;}}}void dfs(int u,int fa,int val){if(val>mx){mx=val;pos=u;}for(int i=hd[u];i;i=v[i].nxt)if(v[i].to!=fa)dfs(v[i].to,u,val+1);}int main(){while(scanf("%d%d",&n,&m)){if(n==0&&m==0)break;cnt=dcnt=tim=0;memset(hd,0,sizeof(hd));memset(dfn,0,sizeof(dfn));memset(low,0,sizeof(low));for(int i=1;i<=m;i++){scanf("%d%d",&x[i],&y[i]);addedge(x[i],y[i]),addedge(y[i],x[i]);}for(int i=1;i<=n;i++)if(!dfn[i])tarjan(i,0);if(dcnt==1){printf("0\n");continue;}cnt=0;memset(hd,0,sizeof(hd));for(int i=1;i<=m;i++)if(belong[x[i]]!=belong[y[i]])addedge(belong[x[i]],belong[y[i]]),addedge(belong[y[i]],belong[x[i]]);mx=0;memset(dis,0,sizeof(dis));dfs(1,0,0);memset(dis,0,sizeof(dis));dfs(pos,0,0);printf("%d\n",dcnt-mx-1);}return 0;}



0 0
原创粉丝点击