题意:
给出一个n个点m条边的无向图,询问添加一条边后图中最少有多少个桥?
题解:
对无向图缩点,缩点后的DAG有多少条边即有多少个桥。
很明显添加一条边(u, v)后,DAG中的(u, v)路径上的桥都会失效。
那么我们直接找一条最长的路径即直径即可。
代码:
/*
* @Author : Nightmare
*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define ls 2 * rt
#define rs 2 * rt + 1
#define gcd(a,b) __gcd(a,b)
#define eps 1e-8
#define lowbit(x) (x&(-x))
#define N 200005
#define M 2000005
#define mod 1000000007
#define inf 0x3f3f3f3f
int n, m, cnt, rt, low[N], dfn[N], dep[N], vis[M];
int st[N], top, scc[N], sc, bridge;
int head[N], to[M], nxt[M], tot;
vector<int> edge[N];
void add(int a, int b){ to[++tot] = b; nxt[tot] = head[a]; head[a] = tot; }
void init(){
tot = 1; cnt = rt = sc = top = bridge = 0;
for(int i = 1 ; i <= n ; i ++) edge[i].clear();
for(int i = 1 ; i <= n ; i ++) head[i] = dfn[i] = low[i] = scc[i] = 0;
}
void tarjan(int u){
low[u] = dfn[u] = ++cnt; st[++top] = u;
for(int i = head[u] ; i ; i = nxt[i]){
int v = to[i];
if(vis[i]) continue;
vis[i] = vis[i ^ 1] = 1;
if(!dfn[v]) tarjan(v), low[u] = min(low[u], low[v]);
else if(!scc[v]) low[u] = min(low[u], dfn[v]);
}
if(low[u] == dfn[u]){
sc ++; int v;
do{
v = st[top --]; scc[v] = sc;
}while(u != v);
}
}
void BFS(int S){
queue<int> que; que.push(S);
memset(dep, 0, sizeof(dep)); dep[S] = 1;
while(!que.empty()){
int u = que.front(); que.pop();
for(auto &v : edge[u]){
if(!dep[v]){
dep[v] = dep[u] + 1;
que.push(v);
if(dep[v] > dep[rt]) rt = v;
}
}
}
}
void solve(){
init();
for(int i = 1, a, b; i <= m ; i ++) scanf("%d %d", &a, &b), add(a, b), add(b, a);
for(int i = 2 ; i <= tot ; i ++) vis[i] = 0;
for(int i = 1 ; i <= n ; i ++) if(!dfn[i]) tarjan(i);
for(int i = 2 ; i <= tot ; i += 2){
if(scc[to[i]] != scc[to[i ^ 1]]){
edge[scc[to[i]]].push_back(scc[to[i ^ 1]]);
edge[scc[to[i ^ 1]]].push_back(scc[to[i]]);
bridge ++;
}
}
BFS(scc[1]);
BFS(rt);
cout << bridge - dep[rt] + 1 << '\n';
}
signed main(){
#ifndef ONLINE_JUDGE
freopen("F:\\in.txt", "r", stdin);
#endif
while(~scanf("%d %d", &n, &m) && (n + m)) solve();
#ifndef ONLINE_JUDGE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}