给定一个无向图,问最少添加多少条边,使得这个图成为连通图
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
const int maxn = 1111;
vector<int> G[maxn], P[maxn];
int pre[maxn], bccno[maxn], dfs_clock, bcc_cnt;
int dfs1(int u, int fa){
int lowu = pre[u] = ++dfs_clock;
for (int i = 0; i < G[u].size(); i++){
int v = G[u][i];
if (!pre[v]){
int lowv = dfs1(v, u);
lowu = min(lowu, lowv);
if (lowv > pre[u]){
P[u].push_back(v);
P[v].push_back(u);
}
}
else if (pre[v] < pre[u] && v != fa)
lowu = min(lowu, pre[v]);
}
return lowu;
}
void dfs2(int u, int fa){
bccno[u] = bcc_cnt;
for (int i = 0; i < G[u].size(); i++){
int v = G[u][i];
bool f = 1;
for (int j = 0; j < P[u].size(); j++){
int vv = P[u][j];
if (v == vv){
f = 0; break;
}
}
if (!f || bccno[v]) continue;
dfs2(v, u);
}
}
void find_bcc(int n){
memset(pre, 0, sizeof(pre));
memset(bccno, 0, sizeof(bccno));
dfs_clock = bcc_cnt = 0;
for (int i = 0; i < n; i++)
if (!pre[i]) dfs1(i, -1);
for (int i = 0; i < n; i++)
if (!bccno[i]){
bcc_cnt += 1;
dfs2(i, -1);
}
}
int dg[maxn];
int main(){
//freopen("in.txt", "r", stdin);
int n, m;
while(~scanf("%d%d", &n, &m)){
for (int i = 0; i <= n; i++){
G[i].clear(); P[i].clear();
}
for (int i = 0; i < m; i++){
int x, y;
scanf("%d%d", &x, &y);
x -= 1; y -= 1;
G[x].push_back(y);
G[y].push_back(x);
}
find_bcc(n);
memset(dg, 0, sizeof(dg));
for (int u = 0; u < n; u++)
for (int i = 0; i < G[u].size(); i++){
int v = G[u][i];
if (bccno[u] != bccno[v]) dg[bccno[u]] += 1;
}
int a = 0;
for (int i = 1; i <= bcc_cnt; i++){
if (dg[i] == 1) a += 1;
if (dg[i] == 0) a += 2;
}
int ans = (a + 1) / 2;
if (bcc_cnt == 1) ans = 0;
printf("%d\n", ans);
}
return 0;
}