# 【bzoj4998】星球联盟 LCT+并查集

1≤N,M,P≤200000

5 3 4
1 2
4 3
4 5
2 3
1 3
4 5
2 4

No
3
2
5

LCT+并查集，【bzoj2959】长跑 的简化版。

#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 200010
using namespace std;
int bl[N] , fa[N] , c[2][N] , w[N] , rev[N] , con[N];
int find(int x)
{
return x == bl[x] ? x : bl[x] = find(bl[x]);
}
int getcon(int x)
{
return x == con[x] ? x : con[x] = getcon(con[x]);
}
void pushdown(int x)
{
if(rev[x])
{
int l = c[0][x] , r = c[1][x];
swap(c[0][l] , c[1][l]) , swap(c[0][r] , c[1][r]);
rev[l] ^= 1 , rev[r] ^= 1 , rev[x] = 0;
}
}
bool isroot(int x)
{
return c[0][find(fa[x])] != x && c[1][find(fa[x])] != x;
}
void update(int x)
{
if(!isroot(x)) update(find(fa[x]));
pushdown(x);
}
void rotate(int x)
{
int y = find(fa[x]) , z = find(fa[y]) , l = (c[1][y] == x) , r = l ^ 1;
if(!isroot(y)) c[c[1][z] == y][z] = x;
fa[x] = z , fa[y] = x , fa[c[r][x]] = y , c[l][y] = c[r][x] , c[r][x] = y;
}
void splay(int x)
{
int y , z;
update(x);
while(!isroot(x))
{
y = find(fa[x]) , z = find(fa[y]);
if(!isroot(y))
{
if((c[0][y] == x) ^ (c[0][z] == y)) rotate(x);
else rotate(y);
}
rotate(x);
}
}
void access(int x)
{
int t = 0;
while(x) splay(x) , c[1][x] = t , t = x , x = find(fa[x]);
}
void makeroot(int x)
{
access(x) , splay(x) , swap(c[0][x] , c[1][x]) , rev[x] ^= 1;
}
void link(int x , int y)
{
makeroot(x) , fa[x] = y , con[getcon(x)] = getcon(y);
}
void dfs(int x , int y)
{
if(!x) return;
bl[x] = y , w[y] += w[x];
dfs(c[0][x] , y) , dfs(c[1][x] , y);
}
int add(int x , int y)
{
x = find(x) , y = find(y);
if(x == y) return w[x];
else if(getcon(x) != getcon(y))
{
return -1;
}
makeroot(x) , access(y) , splay(y);
dfs(c[0][y] , y);
return w[y];
}
int main()
{
int n , m , p , i , x , y , t;
scanf("%d%d%d" , &n , &m , &p);
for(i = 1 ; i <= n ; i ++ ) bl[i] = con[i] = i , w[i] = 1;
for(i = 1 ; i <= m ; i ++ ) scanf("%d%d" , &x , &y) , add(x , y);
for(i = 1 ; i <= p ; i ++ )
{
scanf("%d%d" , &x , &y) , t = add(x , y);
if(~t) printf("%d\n" , t);
else puts("No");
}
return 0;
}


posted @ 2017-08-22 19:45  GXZlegend  阅读(799)  评论(0编辑  收藏  举报