1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| #include <cstdio> #include <algorithm> #include <cstring> #include <queue> #define MAXN 200005 using namespace std;
int n, m, q, t, ans, cnt, head[MAXN], a[MAXN], b[MAXN], f[MAXN]; int id, tot, top, low[MAXN], dfn[MAXN], c[MAXN], dep[MAXN], fa[MAXN], sta[MAXN]; bool bridge[MAXN*2], tag[MAXN*2], vis[MAXN];
struct Edge {int next, to, dis;} edge[MAXN*2];
void init() { cnt=1; ans=id=tot=top=0; for(int i=0; i<=MAXN-5; i++) head[i]=low[i]=dfn[i]=dep[i]=c[i]=vis[i]=0; for(int i=1; i<=MAXN; i++) f[i]=i; for(int i=0; i<=MAXN*2-5; i++) bridge[i]=tag[i]=0; }
void addedge(int from, int to) { edge[++cnt].next=head[from]; edge[cnt].to=to; head[from]=cnt; }
void tarjan(int x, int in) { low[x]=dfn[x]=++id; for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(!dfn[to]) { tarjan(to, i); low[x]=min(low[x], low[to]); if(low[to]>dfn[x]) bridge[i]=bridge[i^1]=1; } else if(i!=(in^1)) low[x]=min(low[x], dfn[to]); } }
void dfs1(int x, int tot) { c[x]=tot; vis[x]=1; for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(bridge[i] || vis[to]) continue; dfs1(to, tot); } }
void dfs2(int x, int father) { fa[x]=father; for(int i=head[x]; i; i=edge[i].next) { int to=edge[i].to; if(to==father) continue; dep[to]=dep[x]+1; ans++; dfs2(to, x); } }
int find(int x) { if(f[x]!=x) f[x]=find(f[x]); return f[x]; }
void lca(int x, int y) { x=find(x); y=find(y); while(x!=y) { if(dep[x]>dep[y]) sta[++top]=x, x=find(fa[x]); else sta[++top]=y, y=find(fa[y]); ans--; } while(top) f[sta[top--]]=x; }
int main() { while(scanf("%d%d", &n, &m) && n && m) { init(); for(int i=1; i<=m; i++) { scanf("%d%d", &a[i], &b[i]); addedge(a[i], b[i]); addedge(b[i], a[i]); } tarjan(1, 0); for(int i=1; i<=n; i++) if(!vis[i]) dfs1(i, ++tot);
cnt=1; for(int i=1; i<=MAXN-5; i++) head[i]=0; for(int i=1; i<=m; i++) { if(c[a[i]]==c[b[i]]) continue; addedge(c[a[i]], c[b[i]]); addedge(c[b[i]], c[a[i]]); } dfs2(1, 0);
printf("Case %d:\n", ++t); scanf("%d", &q); for(int i=1; i<=q; i++) { int x, y; scanf("%d%d", &x, &y); lca(c[x], c[y]); printf("%d\n", ans); } } }
|