1. 程式人生 > >UVA 11987 Almost Union-Find [並查集]

UVA 11987 Almost Union-Find [並查集]

題目傳送門

並查集裸題,全當練手

#include<cstdio>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN = 100010;
int n,m;
int father[MAXN];
int sum[MAXN],num[MAXN];
template<class T>inline void readin(T &res){
    static char ch;
    while((ch=getchar())<'0'
||ch>'9');res=ch-48; while((ch=getchar())<='9'&&ch>='0')res=res*10+ch-48; } void init(){ for(int i=1;i<=n;i++){ father[i]=i+n; father[i+n]=i+n; sum[i+n]=i; num[i+n]=1; } } int find(int x){ return father[x]!=x?father[x]=find(father[x]):x; } int
main(){ int mark,x,y; while(scanf("%d%d",&n,&m)!=EOF){ init(); for(register int i=0;i<m;i++){ readin(mark); if(mark==1){ readin(x),readin(y); int fx=find(x),fy=find(y); if(fx!=fy){ father[fx]=fy; sum[fy]+=sum[fx]; num[fy]+=num[fx]; } }else
if(mark==2){ readin(x),readin(y); int fx=find(x),fy=find(y); if(fx!=fy){ father[x]=fy; sum[fy]+=x,sum[fx]-=x; num[fy]++,num[fx]--; } }else{ scanf("%d",&x); int fx=find(x); printf("%d %d\n",num[fx],sum[fx]); } } } return 0; }