Language:
Description A network administrator manages a large network. The network consists of N computers and M links between pairs of computers. Any pair of computers are connected directly or indirectly by successive links, so data can be transformed between any two computers. The administrator finds that some links are vital to the network, because failure of any one of them can cause that data can't be transformed between some computers. He call such a link a bridge. He is planning to add some new links one by one to eliminate all bridges. You are to help the administrator by reporting the number of bridges in the network after each new link is added. Input The input consists of multiple test cases. Each test case starts with a line containing two integers N(1 ≤ N ≤ 100,000) and M(N - 1 ≤ M ≤ 200,000). Output For each test case, print a line containing the test case number( beginning with 1) and Q lines, the i-th of which contains a integer indicating the number of bridges in the network after the first i new links are added. Print a blank line after the output for each test case. Sample Input 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 Sample Output Case 1: 1 0 Case 2: 2 0 Source |
题意:给定n个点m条边构成的无向图,有k次询问添加(u,v)边问桥的个数。
思路:先tarjan求出桥的个数以及哪些边为桥,然后对于每次询问(u,v),u-> lca(u,v) v->lca(u,v)的路径中如果之前是桥,那么添加(u,v)之后就不是桥了,程序中bri[i]=0,bri_cnt--,详见代码:
(注意:MAXN设大点,不然RE)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN=100000+100;
struct Edge
{
int v;
int next;
}edge[MAXN<<2];
int n,m,edge_cnt,dfs_clock,top,bri_cnt,k;
int head[MAXN],dfn[MAXN],low[MAXN],bri[MAXN<<2],fa[MAXN],ins[MAXN],s[MAXN];
void init()
{
edge_cnt=dfs_clock=top=bri_cnt=0;
memset(head,-1,sizeof(head));
memset(dfn,0,sizeof(dfn));
memset(ins,0,sizeof(ins));
memset(bri,0,sizeof(bri));
for(int i=1;i<=n;i++)
fa[i]=i;
}
void addedge(int u,int v)
{
edge[edge_cnt].v=v;
edge[edge_cnt].next=head[u];
head[u]=edge_cnt++;
}
void tarjan(int u,int f)
{
dfn[u]=low[u]=++dfs_clock;
ins[u]=1; s[top++]=u;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(v==f)
continue;
if(!dfn[v])
{
fa[v]=u;
tarjan(v,u);
low[u]=min(low[u],low[v]);
if(low[v]>dfn[u])
bri[v]=1,bri_cnt++;
}
else if(ins[v])
low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u])
{
ins[u]=0;
while(s[--top]!=u)
ins[s[top]]=0;
}
}
void lca(int u,int v)
{
while(dfn[u]>dfn[v])
{
if(bri[u])
bri[u]=0,bri_cnt--;
u=fa[u];
}
while(dfn[v]>dfn[u])
{
if(bri[v])
bri[v]=0,bri_cnt--;
v=fa[v];
}
while(u!=v)
{
if(bri[u])
bri[u]=0,bri_cnt--;
if(bri[v])
bri[v]=0,bri_cnt--;
u=fa[u],v=fa[v];
}
}
int main()
{
//freopen("text.txt","r",stdin);
int kase=0;
while(~scanf("%d%d",&n,&m) && n+m)
{
kase++;
printf("Case %d:\n",kase);
int u,v;
init();
for(int i=0;i<m;i++)
{
scanf("%d%d",&u,&v);
addedge(u,v); addedge(v,u);
}
tarjan(1,1);
scanf("%d",&k);
for(int i=0;i<k;i++)
{
scanf("%d%d",&u,&v);
lca(u,v);
printf("%d\n",bri_cnt);
}
printf("\n");
}
return 0;
}