好久不写带权并查集,TLE和WA了好几发也没想出来这题怎么写。设方块
的权值为
,其含义为下面有多少个方块,设
为其上面的方块数量,初始时
,当我们合并两个集合的时候:
在
时更新了
,在
集合合并到
集合后,因为
的祖先还没有改变,那么之后用到
时
即可路径压缩将
的祖先设置为
,其下正确的方块个数也会更新为
,这便是带权并查集的神奇之处,本题用
数组表示上面的方块数也很神奇
#include <cstdio>
#include <math.h>
#include <vector>
#include <iostream>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define ins insert
#define Vector Point
#define lowbit(x) (x&(-x))
#define mkp(x,y) make_pair(x,y)
#define mem(a,x) memset(a,x,sizeof a);
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<double,double> pdd;
const double eps=1e-8;
const double pi=acos(-1.0);
const int inf=0x3f3f3f3f;
const double dinf=1e300;
const ll INF=1e18;
const int Mod=1e9+7;
const int maxn=3e4+10;
int f[maxn],s[maxn],v[maxn];
int Find(int x){
if(f[x]!=x){
int t=f[x];
f[x]=Find(f[x]);
v[x]+=v[t];
}
return f[x];
}
void Union(int x,int y){
int fx=Find(x);
int fy=Find(y);
if(fx!=fy){
f[fx]=fy;
v[fx]=s[fy];
s[fy]+=s[fx];
}
}
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
//ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int t,x,y;
char op;
for(int i=1;i<maxn;i++){
f[i]=i,s[i]=1;
}
scanf("%d",&t);
while(t--){
getchar();
scanf("%c",&op);
if(op=='C'){
scanf("%d",&x);
int fx=Find(x);
printf("%d\n",v[x]);
}else{
scanf("%d%d",&x,&y);
Union(x,y);
}
}
return 0;
}