当前位置: 代码迷 >> 综合 >> poj 3177 Redundant Paths 边双连通分量
  详细解决方案

poj 3177 Redundant Paths 边双连通分量

热度:58   发布时间:2024-01-19 06:25:59.0

题意:

跟poj 3352 一样,给一个有桥的无向图,求最少加多少条边后能变为边双连通的。

思路:

求边双连通分量,缩点后得到一颗树,求得树叶树leaf后答案为(leaf+1)/2。

代码:

//poj 3177
//sepNINE
#include <iostream>
#include <stack>
using namespace std;
const int maxN=5024;
const int maxM=20024;
struct Edge
{int v,next;
}edge[maxM]; 
int n,m,e,t,cnt;
int head[maxN],dfn[maxN],low[maxN],inStack[maxN],par[maxN],belong[maxN];
stack<int> mystack;
void tarjan(int h)
{inStack[h]=1;mystack.push(h);	dfn[h]=low[h]=++t;for(int i=head[h];i!=-1;i=edge[i].next){int v=edge[i].v;if(!dfn[v]){par[v]=h;tarjan(v);low[h]=min(low[h],low[v]);}else if(inStack[v]&&v!=par[h]){low[h]=min(low[h],dfn[v]);	} }if(low[h]==dfn[h]){int k;++cnt;do{k=mystack.top();belong[k]=cnt;mystack.pop();inStack[k]=0;		}while(low[k]!=dfn[k]);}return ;
}
void solve()
{memset(dfn,0,sizeof(dfn));memset(low,0,sizeof(low));memset(inStack,0,sizeof(inStack));memset(belong,0,sizeof(belong));while(!mystack.empty()) mystack.pop();int i,j;for(i=1;i<=n;++i)if(!dfn[i]){par[i]=-1;tarjan(i);	}int leaf=0,d[maxN];memset(d,0,sizeof(d));for(i=1;i<=n;++i)for(j=head[i];j!=-1;j=edge[j].next){int u=belong[i],v=belong[edge[j].v];if(u!=v){++d[u];++d[v];}					}for(i=1;i<=cnt;++i)if(d[i]==2)++leaf;printf("%d\n",(leaf+1)/2);		return ;	
}int main()
{while(scanf("%d%d",&n,&m)==2){t=0;e=0;cnt=0;memset(head,-1,sizeof(head));while(m--){int a,b,flag=0;scanf("%d%d",&a,&b);for(int i=head[a];i!=-1;i=edge[i].next)if(edge[i].v==b)flag=1;if(flag==1)continue;edge[e].v=b;edge[e].next=head[a];head[a]=e++;edge[e].v=a;edge[e].next=head[b];head[b]=e++;}	solve();}return 0;	
} 


  相关解决方案