POJ 3177 Redundant Paths (边双连通+缩点)
<題目鏈接>
<轉(zhuǎn)載于 >>>? >
題目大意:
有n個(gè)牧場(chǎng),Bessie 要從一個(gè)牧場(chǎng)到另一個(gè)牧場(chǎng),要求至少要有2條獨(dú)立的路可以走。現(xiàn)已有m條路,求至少要新建多少條路,使得任何兩個(gè)牧場(chǎng)之間至少有兩條獨(dú)立的路。兩條獨(dú)立的路是指:沒有公共邊的路,但可以經(jīng)過同一個(gè)中間頂點(diǎn)。
解題分析:
在同一個(gè)邊雙連通分量中,任意兩點(diǎn)都有至少兩條獨(dú)立路可達(dá),所以同一個(gè)邊雙連通分量里的所有點(diǎn)可以看做同一個(gè)點(diǎn)。
縮點(diǎn)后,新圖是一棵樹,樹的邊就是原無(wú)向圖的橋。
現(xiàn)在問題轉(zhuǎn)化為:在樹中至少添加多少條邊能使圖變?yōu)殡p連通圖。
結(jié)論:添加邊數(shù)=(樹中度為1的節(jié)點(diǎn)數(shù)+1)/2
具體方法為,首先把兩個(gè)最近公共祖先最遠(yuǎn)的兩個(gè)葉節(jié)點(diǎn)之間連接一條邊,這樣可以把這兩個(gè)點(diǎn)到祖先的路徑上所有點(diǎn)收縮到一起,因?yàn)橐粋€(gè)形成的環(huán)一定是雙連通的。然后再找兩個(gè)最近公共祖先最遠(yuǎn)的兩個(gè)葉節(jié)點(diǎn),這樣一對(duì)一對(duì)找完,恰好是(leaf+1)/2次,把所有點(diǎn)收縮到了一起。
#include <cstdio> #include <cstring> #include <algorithm> using namespace std;const int N = 5e3+5 , M = 1e4+5; #define clr(a,b) memset(a,b,sizeof(a)) struct Edge{int to,next; }edge[M<<1];int head[N],low[N],dfn[N],belong[N],deg[N],stk[N],instk[N]; int n,m,tot,cnt,top,scc; void addEdge(int u,int v){edge[tot].to=v,edge[tot].next=head[u];head[u]=tot++; } void init(){tot=cnt=top=scc=0;clr(head,-1);clr(low,0);clr(dfn,0);clr(instk,0);clr(deg,0); } void Tarjan(int u,int fa){low[u]=dfn[u]=++cnt;stk[++top]=u;instk[u]=1;for(int i=head[u];~i;i=edge[i].next){int v=edge[i].to;if(i==(fa^1))continue; //不能用搜索樹上的邊來(lái)更新low值,這種寫法能夠用來(lái)處理重邊的情況if(!dfn[v]){Tarjan(v,i);low[u]=min(low[u],low[v]);}else if(instk[v]) //此時(shí)棧里的所有元素均屬于同一邊雙連通分量,找連通分量的根的時(shí)候一定要規(guī)定這點(diǎn),否則可能會(huì)與其他連通分量的dfn比較low[u]=min(low[u],dfn[v]); //low值全部等于該雙連通分量中最先遍歷的點(diǎn)dfn值 }if(dfn[u]==low[u]){++scc; while(true){int v=stk[top--];instk[v]=0;belong[v]=scc; //將該聯(lián)通塊中的所有點(diǎn)全部縮點(diǎn)染色if(v==u)break;} } } int main(){while(scanf("%d%d",&n,&m)!=EOF){init();for(int i=1;i<=m;i++){int u,v;scanf("%d%d",&u,&v);addEdge(u,v),addEdge(v,u);}Tarjan(1,-1);for(int i=1;i<=n;i++){for(int j=head[i];j!=-1;j=edge[j].next){int v=edge[j].to;if(belong[i]!=belong[v])deg[belong[i]]++; //求出縮點(diǎn)后每個(gè)點(diǎn)的度 }}int sum=0;for(int i=1;i<=scc;i++)if(deg[i]==1)sum++; //尋找度為1的葉子節(jié)點(diǎn) int ans=(sum+1)/2; printf("%d\n",ans);} }?
?
?
2018-11-07
轉(zhuǎn)載于:https://www.cnblogs.com/00isok/p/9919653.html
總結(jié)
以上是生活随笔為你收集整理的POJ 3177 Redundant Paths (边双连通+缩点)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3.1 普通型生成函数
- 下一篇: Django-路由控制