首先求出所有边双连通分量,缩点后得到一棵树。之后每次加边就将边上两个点(新树的点)到他们lca路径上的桥去掉。
由于用边代表桥比较麻烦,所以在后面处理时是以边的终点标记桥。
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <stack>
#include <vector>
#include <string.h>
#include <queue>
#define msc(X) memset(X,-1,sizeof(X))
#define ms(X) memset(X,0,sizeof(X))
typedef long long LL;
using namespace std;
const int MAXN=100010;
const int MAXM=400010+3000;
struct _Edge
{
int to,next;
bool cut;
}edge[MAXM];
int hd[MAXN],tot;
int Low[MAXN],DFN[MAXN],Stack[MAXN],Belong[MAXN];
int Index,top;
int block;
bool Instack[MAXN];
int bridge;
void addedge(int u,int v)
{
edge[tot].to=v;
edge[tot].next=hd[u];
edge[tot].cut=false;
hd[u]=tot++;
}
void Tarjan(int u,int pre)
{
int v;
Low[u]=DFN[u]=++Index;
Stack[top++]=u;
Instack[u]=true;
int pre_cnt=0;
for(int i=hd[u];i!=-1;i=edge[i].next)
{
v=edge[i].to;
if(v==pre&&pre_cnt==0) {pre_cnt++;continue;}
if(!DFN[v]){
Tarjan(v,u);
if(Low[u]>Low[v]) Low[u]=Low[v];
if(Low[v]>DFN[u]){
bridge++;
edge[i].cut=true;
edge[i^1].cut=true;
}
}
else if(Instack[v]&&Low[u]>DFN[v])
Low[u]=DFN[v];
}
if(Low[u]==DFN[u]){
block++;
do{
v=Stack[--top];
Instack[v]=false;
Belong[v]=block;
}while(v!=u);
}
}
void inti(void)
{
ms(Instack);
ms(DFN);
ms(Belong);
Index=top=block=bridge=tot=0;
msc(hd);
}
int fa[MAXN];
int deg[MAXN];
bool a[MAXN];
vector<int> son[MAXN];
void lca_bfs(int root)
{
queue<int > que;
msc(deg);
deg[root]=0;
fa[root]=root;
a[root]=false;
que.push(root);
while(!que.empty()){
int tmp=que.front();
que.pop();
int sz=son[tmp].size();
for(int i=0;i<sz;i++)
{
int v=son[tmp][i];
if(deg[v]!=-1) continue;
//if(v==fa[tmp]) continue;不要这样写,会mle
deg[v]=deg[tmp]+1;
fa[v]=tmp;
a[v]=true;
que.push(v);
}
}
}
int ans;
void LCA(int u,int v)
{
if(deg[u]>deg[v]) swap(u,v);
while(deg[v]>deg[u]){
if(a[v]) {a[v]=false;ans--;}
v=fa[v];
}
if(u==v) return ;
while(u!=v){
if(a[u]) {a[u]=false;ans--;}
if(a[v]) {a[v]=false;ans--;}
u=fa[u],v=fa[v];
}
}
int main(int argc, char const *argv[])
{
int n,m,ti=0;
while(scanf("%d %d",&n,&m)==2&&(n||m))
{
inti();
while(m--){
int a,b;
scanf("%d %d",&a,&b);
addedge(a,b);
addedge(b,a);
}
Tarjan(1,-1);
printf("Case %d:\n",++ti );
ans=block-1;
//缩点
for(int i=1;i<=block;i++)
son[i].clear();
for(int u=1;u<=n;u++)
for(int i=hd[u];i!=-1;i=edge[i].next)
if(edge[i].cut)
{
son[Belong[u]].push_back(Belong[edge[i].to]);
son[Belong[edge[i].to]].push_back(Belong[u]);
}
ms(a);
lca_bfs(1);
int q;
scanf("%d",&q);
while(q--){
int a,b;
scanf("%d %d",&a,&b);
LCA(Belong[a],Belong[b]);
printf("%d\n",ans );
}
putchar('\n');
}
return 0;
}
/*
3 2
1 2
2 3
2
1 2
1 3
4 4
1 2
2 1
2 3
1 4
2
1 2
3 4
0 0
4 3
1 2
2 3
1 4
3
2 1
1 2
3 4
0 0
*/