题意
n个点r条无向边,求至少要加多少条边能够让这个图变成双连通分量
思路
tarjan缩点之后,因为无向图存图的时候是建双向边,所以统计出度为1的点的个数ans,则至少需要加(ans+1)/2条边能够使这个图变成双连通分量。
#include<iostream>
#include<queue>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
const int MAX_N = 1010;
const int MAX_M = 2010;
struct edge {
int v, nxt;
}e[MAX_M];
stack<int>S;
int id[MAX_N], scc_cnt;
int dfn[MAX_N], low[MAX_N];
int head[MAX_N], cnt = 1, timestamp;
int in[MAX_N], out[MAX_N];
int in_stack[MAX_N];
int n, m;
void init() {
while (!S.empty())S.pop();
memset(dfn, 0, sizeof dfn);
memset(low, 0, sizeof low);
memset(head, -1, sizeof head);
memset(id, 0, sizeof id);
memset(in, 0, sizeof in);
memset(out, 0, sizeof out);
memset(in_stack, 0, sizeof in_stack);
cnt = 1, timestamp = 0, scc_cnt = 0;
}
void add(int u,int v) {
e[cnt].v = v;
e[cnt].nxt = head[u];
head[u] = cnt++;
}
void tarjan(int x, int fa) {
dfn[x] = low[x] = ++timestamp;
S.push(x);
in_stack[x] = 1;
for (int i = head[x]; ~i; i = e[i].nxt) {
int v = e[i].v;
if (v == fa)continue;
if (!dfn[v]) {
tarjan(v, x);
low[x] = min(low[x], low[v]);
}
else if (in_stack[v]) {
low[x] = min(low[x], dfn[v]);
}
}
if (dfn[x] == low[x]) {
scc_cnt++;
while (1) {
int temp = S.top();
S.pop();
//cout << temp << " ";
in_stack[temp] = 0;
id[temp] = scc_cnt;
if (temp == x)break;
}
}
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
init();
for (int i = 1; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
add(x, y); add(y, x);
}
for (int i = 1; i <= n; i++) {
if (!dfn[i])tarjan(i, 0);
}
for (int i = 1; i <= n; i++) {
for (int j = head[i]; ~j; j = e[j].nxt) {
int v = e[j].v;
int a = id[i], b = id[v];
if (a != b) {
in[b]++;
out[a]++;
}
}
}
int ans = 0;
for (int i = 1; i <= scc_cnt; i++) {
if (out[i] == 1)ans++;
}
cout << (ans + 1) / 2 << endl;
}
return 0;
}