LCA+tarjan
http://poj.org/problem?id=3694
给一副图,(可能有环,但联通)然后给定q次询问,每次询问的u,v是要加上去的边,问加上去后,若图的边联通度还是1时,有多少条桥
利用并查集缩点,先用tarjan求出总的桥的数量;
利用tarjan中的dfn来找每次u,v的LCA,u到v路径就会成为一个环(记得在跳找LCA时遇到桥标记要取消标记,因为已成环了嘛);
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> using namespace std; const int M=2e5+5; struct node{ int u,v,nextt; }e[M<<1]; int ans,tot,cnt,low[M],dfn[M],head[M],vis[M],qiao[M],fa[M]; void addedge(int u,int v){ e[tot].v=v; e[tot].nextt=head[u]; head[u]=tot++; e[tot].v=u; e[tot].nextt=head[v]; head[v]=tot++; } void dfs(int u,int f){ vis[u]=1; dfn[u]=low[u]=++cnt; for(int i=head[u];~i;i=e[i].nextt){ int v=e[i].v; if(!vis[v]){ dfs(v,u); fa[v]=u; low[u]=min(low[u],low[v]); if(low[v]>dfn[u]){ ans++; qiao[v]=1; } } else if(vis[v]==1&&v!=f){ low[u]=min(low[u],dfn[v]); } } vis[u]=2; } int LCA(int u,int v){ int ans=0; while(dfn[u]>dfn[v]){ if(qiao[u]){ qiao[u]=0; ans++; } u=fa[u]; } while(dfn[v]>dfn[u]){ if(qiao[v]){ qiao[v]=0; ans++; } v=fa[v]; } while(u!=v){ if(qiao[u]){ qiao[u]=0; ans++; } if(qiao[v]){ qiao[v]=0; ans++; } u=fa[u]; v=fa[v]; } return ans; } int n,m; void init(){ cnt=tot=0; memset(head,-1,sizeof(head)); memset(qiao,0,sizeof(qiao)); memset(vis,0,sizeof(vis)); memset(dfn,0,sizeof(dfn)); memset(low,0,sizeof(low)); for(int i=0;i<=n;i++) fa[i]=i; } int main(){ int sign=1; while(~scanf("%d%d",&n,&m)){ if(n==0&&m==0) break; init(); for(int i=1;i<=m;i++){ int u,v; scanf("%d%d",&u,&v); addedge(u,v); } ans=0; dfs(1,1); int k; scanf("%d",&k); printf("Case %d:\n",sign++); for(int i=1;i<=k;i++){ int u,v; scanf("%d%d",&u,&v); ans-=LCA(u,v); printf("%d\n",ans); } putchar('\n'); } return 0; }