Redundant Paths POJ - 3177
题意:
给你一个无向图。问你最少添加几条边可以达到任意pair之间都是双联通。
思路:
-
本题要保证任意pair双联通。可以先求下双联通分量。
-
之后进行缩点。
-
观察下图。蓝点入度为1。那么要保证任意pair双联通。可以按照图里的操作,连两条红边。
-
再考虑下面的情况。
-
那么综合考虑:ans=( ∑ 1 b c c − c n t ( i n [ i ] \sum_{1}^{bcc-cnt}(in[i] ∑1bcc−cnt(in[i]== 1 ) 1) 1)+1)/2。求出所有入度为0的点,那么答案就是上面(分析看两张图,也很好懂)
反思:
- tarjan对于无向图,还是加这句话吧。
if(!dfn[v]){
pre[v]=i^1;
child++;
tarjan(v,u);
low[u]=min(low[u],low[v]);
if(low[v]>=dfn[u]&&(u!=root||child>1))cut[u]=1;
}else if(v!=f&&dfn[v]<dfn[u])low[u]=min(low[u],dfn[v]);
///else if(vis[v])low[u]=min(low[u],dfn[v]);
//有向图,时才用这句话。
AC
#include <iostream>
#include <cstring>
#include <vector>
#include <stack>
#define mst(x,a) memset(x,a,sizeof(x))
#define fzhead EDGE(int _to, int _next)
#define fzbody to(_to), next(_next)
#define For(i,x,y) for(int i=(x); i<=(y); i++)
#define fori(i,x,y) fori(int i=(x); i<(y); i++)
using namespace std;
const int maxn=5000+10;
const int maxm=2e4+10;
struct EDGE{
int to, next;
EDGE(){}
fzhead:fzbody{}
}e[maxm];
int head[maxn], cut[maxn], vis[maxn],bcc[maxn],bcc_num[maxn],col[maxn];
int fa[maxn],pre[maxn], low[maxn], dfn[maxn],bcc_cnt,tot, dfs_clock;
int bridge[maxm],in[maxn];
void add(int bg, int to){
e[tot]=EDGE(to,head[bg]);
head[bg]=tot++;
}
stack<int>s;
void init(){
tot=2;
dfs_clock=bcc_cnt=0;
mst(head,-1);
mst(vis,0);
mst(bcc,0);
mst(fa,0);
mst(pre,0);
mst(low,0);
mst(dfn,0);
mst(bcc_num,0);
mst(col,0);
mst(cut,0);
mst(in,0);
while(!s.empty())s.pop();
}
int root;
void tarjan(int u, int f){
dfn[u]=low[u]=++dfs_clock;
s.push(u);
fa[u]=f;
vis[u]=1;
int child=0;
for(int i=head[u]; i!=-1; i=e[i].next){
int v=e[i].to;
if(!dfn[v]){
pre[v]=i^1;
child++;
tarjan(v,u);
low[u]=min(low[u],low[v]);
if(low[v]>=dfn[u]&&(u!=root||child>1))cut[u]=1;
}else if(v!=f&&dfn[v]<dfn[u])low[u]=min(low[u],dfn[v]);
///else if(vis[v])low[u]=min(low[u],dfn[v]);
//有向图,时才用这句话。
}
if(low[u]==dfn[u]){
col[u]=++bcc_cnt;
vis[u]=0;
int v;
bridge[pre[u]^1]=bridge[pre[u]]=1;
do{
v = s.top();s.pop();
col[v]=bcc_cnt;
bcc_num[bcc_cnt]++;
}while(v!=u);
}
}
int n,m;
int main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n>>m;
int u,v;
init();
For(i,1,m){
cin>>u>>v;
add(u,v);add(v,u);
}
For(u,1,n)if(!dfn[u])dfs_clock=0, root=u, tarjan(u,-1);
//cout<<bcc_cnt<<endl;
For(u,2,n){
int a=col[u],b=col[fa[u]];
if(a==b)continue;
in[a]++,in[b]++;
}
int ans=0;
For(i,1,bcc_cnt)if(in[i]==1)ans++;
//cout<<ans<<endl;
cout<<(ans+1)/2<<endl;
return 0;
}