HDU3635:带权并查集

时间:2019-02-11
本文章向大家介绍HDU3635:带权并查集,主要包括HDU3635:带权并查集使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

HDU3635

题解:找城市编号和总数比较简单,难点在于怎么统计转移次数。

每次转移在根节点加一,每次find子节点的根时,根节点转移次数下放,相当于一个lazy标记下放过程,然后使子节点指向根节点。

代码:

#include <bits/stdc++.h>
using namespace std;
int const N = 10000 + 10;
int T,n,q,sum[N],fa[N],tr[N];
void Init(){
	for(int i=0;i<=n;i++)
		fa[i] = i,sum[i] = 1,tr[i] = 0;
}
int find(int x){
	if(x != fa[x]){
		int t = fa[x];
		fa[x] = find(t);
		tr[x] += tr[t];
	}
	return fa[x];
}
int main(){
	ios::sync_with_stdio(false);
	cin>>T;
	int caser = 0;
	while(T--){
		cin>>n>>q;
		char t;
		int x,y;
		Init();
		cout<<"Case "<<++caser<<":"<<endl;
		for(int i=1;i<=q;i++){
			cin>>t;
			if(t == 'T'){
				cin>>x>>y;   
				int fx = find(x),	fy = find(y);
				if(fx != fy){
					fa[fx] = fy;
					sum[fy] += sum[fx];
					tr[fx]++;
				}
			}else{
				cin>>x;
				int fx = find(x);
				cout<<fx<<" "<<sum[fx]<<" "<<tr[x]<<endl;
			}
		}
	}
	return 0;
}