题意
一张无向联通图,每次询问加一条边,求桥的个数。
题解
算法1:边双缩点之后的图肯定是一棵树,每次在树上连一条边会形成一个环,所以缩点重建图之后每次求LCA更新就好了。
算法2:可以发现
l
o
w
[
  
]
low[\;]
low[]数组的意义有点类似于并查集,
l
o
w
[
u
]
low[u]
low[u]表示u走非树边能到达的最高点,所以如果
l
o
w
[
x
]
=
y
,
l
o
w
[
y
]
=
z
low[x]=y,low[y]=z
low[x]=y,low[y]=z,那么
l
o
w
[
x
]
=
z
low[x]=z
low[x]=z。所以将
l
o
w
[
u
]
low[u]
low[u]的意义由最小时间戳改为搜索树上最浅的点编号,每次更新将两个点合并到LCA上就行了,不需要重新建图。
算法2代码:非常短,连100行都没有到
#include<iostream>
#include<cstdio>
#include<cstring>
#define ll long long
using namespace std;
const int N = 1e6+10;
const int M = 6e6+10;
int n, m, q, cs, e, point[N];
struct EDGE{
int nxt, v;
}edge[M];
int dfn[N], low[N], idx, dpt[N], fa[N], tot;
void add_edge(int u, int v)
{
edge[++e] = (EDGE){point[u], v};
point[u] = e;
}
int Min(int x, int y)
{
return (dfn[x] > dfn[y] ? y : x);
}
void Tarjan(int u, int in_e)
{
dfn[u] = ++idx;
low[u] = u;
for (int i = point[u]; i != -1; i = edge[i].nxt){
if (i == in_e){
continue;
}
int v = edge[i].v;
if (!dfn[v]){
fa[v] = u;
dpt[v] = dpt[u]+1;
Tarjan(v, i^1);
low[u] = Min(low[u], low[v]);
}
else{
low[u] = Min(low[u], v);
}
}
}
int Find(int u)
{
if (low[u] == u) return u;
return low[u] = Find(low[u]);
}
void Union(int v, int u)
{
v = Find(v);
u = Find(u);
if (dpt[v] <= dpt[u]) return;
low[v] = u;
tot--;
}
int main()
{
cs = 0;
while (scanf("%d%d", &n, &m) == 2 && n+m){
printf("Case %d:\n", ++cs);
memset(point, -1, sizeof(point)); e = -1;
for (int i = 1; i <= m; i++){
int x, y;
scanf("%d%d", &x, &y);
add_edge(x, y);
add_edge(y, x);
}
dpt[1] = idx = 0;
memset(dfn, 0, sizeof(dfn));
Tarjan(1, -1);
tot = -1;
for (int i = 1; i <= n; i++)
if (low[i] == i){
tot++;
}
scanf("%d", &q);
for (int i = 1; i <= q; i++){
int x, y;
scanf("%d%d", &x, &y);
x = Find(x);
y = Find(y);
while (x != y){
if (dpt[x] < dpt[y]){
swap(x, y);
}
Union(x, fa[x]);
x = Find(x);
}
printf("%d\n", tot);
}
printf("\n");
}
return 0;
}