[NOI2002]银河英雄传说(并查集)

题目描述

传送门

解题思路

before表示i前面还有几个元素,count[i]表示i所在的有几个元素
并查集

代码

#include
#include
#include
#include
using namespace std;
int father[30005],before[30005],count[30005];
int n,i,x,y;
char z;
int find(int x){
	int f;
	if (father[x]==x) return father[x];
	f=find(father[x]);
	before[x]+=before[father[x]];
	father[x]=f;
	return father[x];
}
void merge(int x,int y){
	int i=find(x);
	int j=find(y);
	father[i]=j;
	before[i]+=count[j];
	count[j]+=count[i];
	return;
}
int main(){
	scanf("%d",&n);
	for (i=1;i<=30001;++i){
		father[i]=i;
		count[i]=1;
		before[i]=0;
	}
	for (i=1;i<=n;++i){
		cin>>z;
		cin>>x>>y;
		if (z=='M')
		  merge(x,y);
		if (z=='C')
		  if (find(x)!=find(y))
		    printf("-1\n");
		  else
		    cout<<abs(before[x]-before[y])-1<<endl;
	}
	return 0;
}

你可能感兴趣的:(题解,并查集,NOI)