预备知识:图的相关知识 https://www.byvoid.com/blog/biconnect/
题目的大致意思是:在一个连通图中,至少添加多少条边,使图中不存在桥
Tarjin时借助并查集,由于桥(删除之后图就不连通的边)不属于任何双连通分量,所以在Tarjin时,把不是桥的边的u,v并在一起,表示u,v在同一个双连通分量里,进行缩点。
一个重要的结论:
若要使得任意一棵树,在增加若干条边后,变成一个双连通图,那么至少增加的边数 =( 这棵树总度数为1的结点数 + 1 )/ 2。
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#define ll long long
#define N 1010
using namespace std;
struct Edge{
int to, next;
}e[N<<1];
int pre[N], dfs_clock, low[N], degree[N], head[N], tol;
void addEdge(int u, int v) {
e[tol].to = v;
e[tol].next = head[u];
head[u] = tol++;
e[tol].to = u;
e[tol].next = head[v];
head[v] = tol++;
}
void dfs(int u, int father) {
low[u] = pre[u] = ++dfs_clock;
for (int i = head[u]; i != -1; i = e[i].next) {
int v = e[i].to;
if (!pre[v]) {
dfs(v, u);
low[u] = min(low[u], low[v]);
} else if (pre[v] < pre[u] && v != father) {
low[u] = min(low[u], pre[v]);
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
// freopen("1.txt", "r", stdin);
#endif
int n, m, u, v;
while(cin >> n >> m) {
memset(head, -1, sizeof(head));
memset(pre, 0, sizeof(pre));
memset(low, 0, sizeof(low));
memset(degree, 0, sizeof(degree));
dfs_clock = 0;
tol = 0;
for (int i = 0; i < m; i++) {
scanf("%d%d", &u, &v);
addEdge(u, v);
}
dfs(1, -1); //连通图,一次深搜就可以遍历所有点
for (u = 1; u <= n; u++) {
for (int i = head[u]; i != -1; i = e[i].next){
v = e[i].to;
if (low[u] != low[v]) {
degree[low[u]]++;
}
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
ans += (degree[i] == 1);
}
cout << (ans+1)/2 << endl;
}
return 0;
}