以下内容为个人理解,有错误地方还请指出。
有时根据问题的需要,要把边双连通分量抽象为一个点,这就叫缩点。
缩点的根据也是low值;同一边双连通分量的点,low值相同,因为对于该边双连通分量dfs树上的根节点u和其子孙节点v,它们之间除了有一条dfs树边组成的路径之外,肯定还有一条包含回边的路径,所以每个点v都能通过一条非dfs树上的路径到达u点,即所有的low[v]=u;
经过缩点后的无向图是一棵树(树的每一条边都是割边),使这棵树变成双连通分量至少需要添加的边的条数==(树的叶子节点+1)/2;
Poj3352 Road Construction
一个连通的无向图,求至少需要添加几条边,原图变为边双联通图;
class POJ_3352
{
private:
int n, r;
vector<int> head[maxn];
int dfn[maxn]; //dfs序,-1表示未遍历,省去vis数组
int depth; //当前dfs序
int low[maxn];
int deg[maxn];
int root;
public:
void ini();
void action();
void tarjan(int rt, int father);
int min_add();
};
void POJ_3352::ini()
{
memset(dfn, -1, sizeof(dfn));
memset(low, -1, sizeof(low));
depth = 1;
}
void POJ_3352::action()
{
ini();
scanf("%d%d", &n, &r);//点,边数量
for (int i = 0; i < r; ++i)
{
int u, v;
scanf("%d%d", &u, &v);
head[u].push_back(v);
head[v].push_back(u);
}
root = 1;
tarjan(1, 1);
printf("%d\n", min_add());
}
void POJ_3352::tarjan(int rt, int father)
{
dfn[rt] = low[rt] = depth++;
for (int i = 0, len = head[rt].size(); i < len; ++i)
{
int v = head[rt][i];
if (dfn[v] == -1)
{
tarjan(v, rt);
low[rt] = min(low[rt], low[v]);
}
else if (v != father)
low[rt] = min(low[rt], dfn[v]);
}
}
int POJ_3352::min_add()
{
mem(deg);
for (int u = 1; u <= n; ++u)
{
for (int j = 0, len = head[u].size(); j < len; ++j)
{
int v = head[u][j];
if (low[u] != low[v])//如果u,v有边,但是low值不一样,则(u,v)是割边
{
deg[low[u]]++;
deg[low[v]]++;
}
}
}
int ans = 0;
for (int i = 1; i <= n; ++i)
{
if (deg[i] / 2 == 1)
ans++;
}
return (ans + 1) / 2;
}
int main()
{
POJ_3352 ans;
ans.action();
}
#END
#TODO
#include <algorithm>
#include <iostream>
#include <numeric>
#include <cstring>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdio>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#define DEBUG
#define LL long long
#define maxn 1100
using namespace std;
typedef vector<int>ve;
vector<ve>head(maxn);
int dfn[maxn],low[maxn],dep_tmp;
bool vis[maxn];
int deg[maxn];
void tarjan(int rt,int father)
{
dfn[rt]=low[rt]=dep_tmp++;
#ifdef DEBUG
cout<<rt<<" dfN=="<<dfn[rt]<<endl;
#endif
vis[rt]=true;
vector<int>&vec=head[rt];
for(int i=0,len=vec.size();i<len;++i)
{
int v=vec[i];
if(!vis[v])
{
tarjan(v,rt);
low[rt]=min(low[rt],low[v]);
}
else if(v!=father)
low[rt]=min(low[rt],dfn[v]);
}
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
dep_tmp=0;
for(int i=0;i<=n;++i)
head[i].clear();
for(int i=0;i<m;++i)
{
int u,v;
scanf("%d%d",&u,&v);
head[u].push_back(v);
head[v ].push_back(u);
}
memset(vis,false,sizeof(vis));
tarjan(1,1);
memset(deg,0,sizeof(deg));
#ifdef DEBUG
cout<<endl;
#endif
for(int i=1;i<=n;++i)
{
#ifdef DEBUG
cout<<low[i]<<" ";
#endif
vector<int>&vec=head[i];
for(int j=0,len=vec.size();j<len;++j)
{
int v=vec[j];
if(low[i]!=low[v])
deg[low[i]]++;
}
}
int ans=0;
for(int i=0;i<=n;++i)
{
if(deg[i]==1)
ans++;
}
printf("%d\n",(ans+1)/2);
}
}
/*
*
11 14
1 2
1 3
1 4
2 5
6 11
2 6
5 6
5 11
3 7
3 8
7 8
4 9
4 10
9 10
*
*
* 对于这组数据,答案明显应该是2,但利用low值缩点的程序答案差不多都是1,
* 把每个点的dfs序输出,发现用tarjan的low值缩点并不严谨啊!
*/