poj 1988 Cube Stacking【带权并查集】

设s[x]为x所在栈里的个数,c[x]表示x下面有几个,合并的时候直接合并s,然后路径压缩的时候更新c即可

#include<iostream>
#include<cstdio>
using namespace std;
const int N=30005;
int n=30000,m,f[N],s[N],c[N];
char o[5];
int read()
{
	int r=0,f=1;
	char p=getchar();
	while(p>'9'||p<'0')
	{
		if(p=='-')
			f=-1;
		p=getchar();
	}
	while(p>='0'&&p<='9')
	{
		r=r*10+p-48;
		p=getchar();
	}
	return r*f;
}
int zhao(int x)
{
	if(x==f[x])
		return x;
	int nw=zhao(f[x]);
	c[x]+=c[f[x]];
	return f[x]=nw;
}
int main()
{
	m=read();
	for(int i=1;i<=n;i++)
		s[i]=1,f[i]=i;
	while(m--)
	{
		scanf("%s",o+1);
		if(o[1]=='M')
		{
			int x=read(),y=read(),fx=zhao(x),fy=zhao(y);
			f[fx]=fy;
			c[fx]=s[fy];
			s[fy]+=s[fx];
		}
		else
		{
			int x=read();
			zhao(x);
			printf("%d
",c[x]);
		}
	}
	return 0;
}
原文地址:https://www.cnblogs.com/lokiii/p/9974294.html