记录编号 226448 评测结果 AAAAAAAAAA
题目名称 [NOI 2002]银河英雄传说 最终得分 100
用户昵称 GravatarHzoi_Go灬Fire 是否通过 通过
代码语言 C++ 运行时间 0.562 s
提交时间 2016-02-18 07:20:32 内存使用 0.66 MiB
显示代码纯文本
#include<cstdio>
#include<string>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<cstring>
#include<stack>
#include<iostream>
#define Mem(arr,val) memset(arr,val,sizeof(arr));
using namespace std;
const int maxn=30004;
int n,before[maxn];
int cunt[maxn],father[maxn];
int Fabs(int);
int Findroot(int);
void Union(int,int);
void Init();
bool Isconnect(int x,int y);
int main()
{
	freopen("galaxy.in","r",stdin);
	freopen("galaxy.out","w",stdout);
	Init();
	return 0;
}
void Init()
{
	memset(before,0,sizeof(before));
	memset(cunt,0,sizeof(cunt));
	memset(father,0,sizeof(father));
	scanf("%d",&n);
	for(int i=1;i<=30000;i++)
	{
		father[i]=i;
		cunt[i]=1;
		before[i]=0;
	}
	getchar();
	for(int i=1;i<=n;i++)
	{
		char ch;
		int x,y;
		scanf("%c%d%d",&ch,&x,&y);
		getchar();
		if(ch=='M')
		{
			int rx=Findroot(x),ry=Findroot(y);
			Union(rx,ry);
		}
		else 
		{
			if(Isconnect(x,y))printf("%d\n",Fabs(before[x]-before[y])-1);
			else printf("-1\n");
		}
	}
}
int Fabs(int x)
{
	if(x>=0)return x;
	else return -x;
}
int Findroot(int x)
{
	if(father[x]!=x)
	{
		int r=Findroot(father[x]);
		before[x]+=before[father[x]];
		father[x]=r;
	}
	return father[x];
}
void Union(int  rx,int ry)
{
	father[rx]=ry;
	before[rx]=cunt[ry];
	cunt[ry]+=cunt[rx];
}
bool Isconnect(int x,int y)
{
	return Findroot(x)==Findroot(y);
}