Language:
Network
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 |
先找出图中的桥,然后并查集缩点,询问的时候,找出连点的LCA,然后把经过的连通分量再合并
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=100010;
int n,m,q;
int pre[maxn],low[maxn],head[maxn],dfs_clock,fa[maxn],cnt;
vector<int> g[maxn];
int find(int x)
{
if(x==head[x])return x;
return head[x]=find(head[x]);
}
void unite(int a,int b)
{
int x=find(a),y=find(b);
head[y]=x;
}
void dfs(int u,int f)
{
low[u]=pre[u]=++dfs_clock;
int len=g[u].size();
for(int i=0;i<len;i++)
{
int v=g[u][i];
if(!pre[v])
{
fa[v]=u;
dfs(v,u);
low[u]=min(low[u],low[v]);
if(low[v]>pre[u])cnt++;
else unite(u,v);
}
else if(pre[v]<pre[u]&&v!=f)
low[u]=min(low[u],pre[v]);
}
}
void find_bcc()
{
memset(pre,0,sizeof(pre));
for(int i=0;i<=n;i++)head[i]=i;
dfs_clock=cnt=0;
dfs(1,-1);
}
void LCA(int a,int b)
{
while(a!=b)
{
while(pre[a]>=pre[b]&&a!=b)
{
if(find(a)!=find(fa[a]))
{
cnt--;
unite(fa[a],a);
}
a=fa[a];
}
while(pre[b]>=pre[a]&&a!=b)
{
if(find(b)!=find(fa[b]))
{
cnt--;
unite(fa[b],b);
}
b=fa[b];
}
}
printf("%d\n",cnt);
}
int main()
{
int cas=1;
while(scanf("%d%d",&n,&m)!=EOF,n||m)
{
for(int i=1;i<=m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
}
find_bcc();
scanf("%d",&q);
printf("Case %d:\n",cas++);
while(q--)
{
int l,r;
scanf("%d%d",&l,&r);
if(find(l)==find(r))printf("%d\n",cnt);
else LCA(l,r);
}
printf("\n");
}
return 0;
}