P1196 [NOI2002]银河英雄传说

题面:https://www.luogu.org/problem/P1196

本题很容易想到开一个数组记当前列中有多少个数,再开一个数组记录每个数字在各自列中离列首的距离,然后直接在路径压缩的时候更新距离即可
注意:这里的find要先进行递归再return

Code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<ctime>
#include<queue>
using namespace std;
const int N=30005;
int m,fa[N],ans[N],num[N];
int find(int x){
	if(x==fa[x]){
		return x;
	}
	int t=find(fa[x]);
	ans[x]+=ans[fa[x]];
	return fa[x]=t;
}
int main(){
	cin>>m;
	for(int i=1;i<=30000;i++){
		fa[i]=i;
		num[i]=1;
	}
	while(m--){
		char z;
		int x,y;
		cin>>z>>x>>y;
		if(z=='M'){
			int fx=find(x);
			int fy=find(y);
			if(fx!=fy){
				fa[fx]=fy;
				ans[fx]+=num[fy];
				num[fy]+=num[fx];
				num[fx]=0;
			}
		}
		else{
			int fx=find(x);
			int fy=find(y);
			if(fx!=fy){
				printf("-1\n");
			}
			else{
				printf("%d\n",abs(ans[x]-ans[y])-1);
			}
		}
	}
	return 0;
}
posted @ 2019-10-08 19:34  prestige  阅读(130)  评论(0编辑  收藏  举报