【CodeVS 1540】银河英雄传说 2002年NOI全国竞赛

noi这么水?
很久没有自己不看题解A题了 ~~~~~~
带权并查集!
CodeVS的数据不合规定??有乱七八糟的字符?? 见我注释掉的读入!【刚又测试 洛谷用被注释掉的那一句也可以A 说明CadeVS数据不合规定!

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
using namespace std;
#define INF 100000000
#define MAXN 1000000 // 永远的10^6
int fa[MAXN],depth[MAXN],m;
int F(int x)
{
	int tmp=fa[x];
	if(fa[x]!=x) 
	{
		fa[x]=F(fa[x]);
		depth[x]+=depth[tmp];
	}
	return fa[x];
}
int wa[MAXN];
int W(int x)
{
	if(wa[x]!=x) wa[x]=W(wa[x]);
	return wa[x];
}
int main()
{
	scanf("%d",&m);char c;
	for(int i=1;i<=30000;i++) fa[i]=i,wa[i]=i;
	for(int x,y,i=1;i<=m;i++)
	{
		//	getchar(),c=getchar();
		cin>>c;
		scanf("%d %d",&x,&y);
		if(c=='M') 
		{
			if(F(x)!=F(y)) 
			{
				int s=F(x),t=W(y);
				fa[s]=t;
				wa[t]=s;
				depth[s]=1;
			}
		}
		if(c=='C')
		{
			if(F(x)!=F(y))
				printf("-1\n");
			else 
				F(x),F(y),printf("%d\n",abs(depth[x]-depth[y])-1);
		}
	}
	return 0;
}
原文地址:https://www.cnblogs.com/ofsxb/p/5114451.html