题目
给一个无向连通图,问至少添加几条边使得去掉图中任意一条边不改变图的连通性(即使得它变为边双连通图)。
求解
- 对原图求出边双联通分量。
- 边双缩点成树。
- 答案为 叶 子 节 点 数 量 + 1 2 \frac{叶子节点数量+1}{2} 2叶子节点数量+1。(依次把两个最远的叶子连边)
代码
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
int n, m;
const int N = 1010;
vector<int> edge[N];
map<int, map<int, int>> mp;
int fa[N], dfn[N], low[N], degree[N], ct;
void tarjan(int u)
{
dfn[u] = low[u] = ++ct;
for (int i = 0; i < edge[u].size(); i++)
{
int v = edge[u][i];
if (!dfn[v])
{
fa[v] = u;
tarjan(v);
low[u] = min(low[u], low[v]);
if (low[v] > low[u])
mp[u][v] = mp[v][u] = 1; //u-v 是桥
}
else if (v != fa[u])
{
low[u] = min(low[u], dfn[v]);
}
}
}
int cnt;
int belong[N];
void dfs(int u)
{
belong[u] = cnt;
for (int i = 0; i < edge[u].size(); i++)
{
int v = edge[u][i];
if (mp[u][v])
continue;
if (dfn[v])
{
dfn[v] = 0;
dfs(v);
}
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= m; i++)
{
int u, v;
cin >> u >> v;
edge[u].push_back(v);
edge[v].push_back(u);
}
tarjan(1); //求桥
for (int i = 1; i <= n; i++)
{
if (dfn[i])
{
++cnt;
dfn[i] = 0;
dfs(i); //边双缩点
}
}
if (cnt == 1) //已经是边双
{
puts("0");
}
else
{
mp.clear();
for (int i = 1; i <= n; i++)
{
for (int j = 0; j < edge[i].size(); j++)
{
int v = edge[i][j];
if (mp[belong[v]][belong[i]] || belong[i] == belong[v])
continue;
mp[belong[v]][belong[i]] = mp[belong[i]][belong[v]] = 1;
degree[belong[v]]++;
degree[belong[i]]++;
}
}
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += degree[belong[i]] == 1; //度为1的节点为叶节点
degree[belong[i]] = -1;
}
cout << (sum + 1) / 2 << endl;
}
return 0;
}