1. 程式人生 > >BZOJ1718: [Usaco2006 Jan] Redundant Paths 分離的路徑

BZOJ1718: [Usaco2006 Jan] Redundant Paths 分離的路徑

play 答案 int 路徑 insert sca sin 向上 hid

n<=5000個點m<=10000條邊的無向圖,求最少加幾條邊使它變成邊雙聯通圖,就是任意兩點間都有至少2條邊不相交的路徑。

tarjan縮點,答案是葉子節點數/2向上取整。

不過要註意這裏的“葉子節點數”是指度數為1的點,並不是最後那棵樹以某個點為根的葉子節點樹。如果找葉子點數一定要以某個點為根,就會像我一樣WA兩次然後發現縮點後只有一個點時答案為0。

技術分享
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 #include<cstdlib>
 5 #include<math.h>
 6
//#include<iostream> 7 using namespace std; 8 9 int n,m; 10 #define maxn 5011 11 #define maxm 20011 12 struct Edge{int to,next;}; 13 struct Graph 14 { 15 Edge edge[maxm]; 16 int first[maxn],le;int n; 17 Graph() {memset(first,0,sizeof(first));le=2;} 18 void in(int x,int y) 19 {
20 Edge &e=edge[le]; 21 e.to=y;e.next=first[x];first[x]=le++; 22 } 23 void insert(int x,int y) 24 { 25 in(x,y); 26 in(y,x); 27 } 28 int low[maxn],dfn[maxn],Time,sta[maxn],top,bel[maxn],tot;bool insta[maxn]; 29 void tarjan(int x,int fa) 30 {
31 low[x]=dfn[x]=++Time; 32 sta[++top]=x;insta[x]=1; 33 for (int i=first[x];i;i=edge[i].next) 34 { 35 Edge &e=edge[i]; 36 if (!dfn[e.to]) tarjan(e.to,i),low[x]=min(low[x],low[e.to]); 37 else if ((i^1)!=fa && insta[e.to]) low[x]=min(low[x],dfn[e.to]); 38 } 39 if (low[x]==dfn[x]) 40 { 41 tot++; 42 while (sta[top]!=x) bel[sta[top]]=tot,insta[sta[top--]]=0; 43 bel[x]=tot,insta[sta[top--]]=0; 44 } 45 } 46 void tarjan() 47 { 48 Time=tot=top=0; 49 memset(dfn,0,sizeof(dfn)); 50 memset(insta,0,sizeof(insta)); 51 for (int i=1;i<=n;i++) if (!dfn[i]) tarjan(i,0); 52 } 53 int dfs(int x,int fa) 54 { 55 int ans=0; 56 bool flag=1; 57 for (int i=first[x];i;i=edge[i].next) 58 { 59 Edge &e=edge[i]; 60 if (e.to!=fa) ans+=dfs(e.to,x),flag=0; 61 } 62 ans+=flag; 63 return ans; 64 } 65 int ye() 66 { 67 int root=1; 68 for (int i=1;i<=n;i++) if (edge[first[i]].next) {root=i;break;} 69 return dfs(root,0); 70 } 71 }g,tg; 72 void build() 73 { 74 tg.n=g.tot; 75 for (int i=1;i<=g.n;i++) 76 for (int j=g.first[i];j;j=g.edge[j].next) 77 { 78 Edge &e=g.edge[j]; 79 if (g.bel[i]!=g.bel[e.to]) tg.in(g.bel[i],g.bel[e.to]); 80 } 81 } 82 int x,y; 83 int main() 84 { 85 scanf("%d%d",&n,&m);g.n=n; 86 for (int i=1;i<=m;i++) scanf("%d%d",&x,&y),g.insert(x,y); 87 g.tarjan(); 88 build(); 89 printf("%d\n",tg.n==1?0:(tg.ye()+1)/2); 90 return 0; 91 }
View Code

BZOJ1718: [Usaco2006 Jan] Redundant Paths 分離的路徑