int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);}
#include <set> #include <map> #include <cmath> #include <queue> #include <vector> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int MAXN=30001; int n,fa[MAXN],dis[MAXN],height[MAXN];char s[5]; int find(int x){ int fx=fa[x]; if(fa[x]!=x){ fa[x]=find(fa[x]);//路径压缩 dis[x]+=dis[fx];//该行只会在合并时遍历一次 } return fa[x]; } void Union(int x,int y){ int fx=find(x),fy=find(y); fa[fy]=fx; dis[fy]=height[fx]; height[fx]+=height[fy]; } int main(){ scanf("%d",&n); for(int i=0;i<MAXN;i++)fa[i]=i,height[i]=1; for(int x,y;n--;){ scanf("%s",s); if(s[0]==‘M‘)scanf("%d%d",&x,&y),Union(x,y); else scanf("%d",&x),printf("%d\n",height[find(x)]-dis[x]-1); } return 0; }
C++-POJ1988-Cube Stacking[数据结构][并查集]
原文:https://www.cnblogs.com/JasonCow/p/12310224.html