hihocoder 1066 并查集

hihocoder 1066

题解:并查集裸题

#include <bits/stdc++.h>
using namespace std;
int const N = 100000 + 10;
int n,k,fa[N];
string s1,s2;
map<string,int>mp;
int find(int x){
	return (x == fa[x]) ? x : (fa[x] = find(fa[x]));
}
void Union(int x,int y){
	int p = find(x),	q = find(y);
	if(p != q)
		fa[p] = q;
}
int main(){
	ios::sync_with_stdio(false);
	cin>>n;
	int cnt = 0;
	for(int i=1;i<=n;i++)	fa[i] = i;
	while(n--){
		cin>>k>>s1>>s2;
		if(!mp[s1])	mp[s1] = ++cnt;
		if(!mp[s2])	mp[s2] = ++cnt;
		int k1 = mp[s1],	k2 = mp[s2];
		if(k == 0){
			Union(k1,k2);
		}else{
			if(find(k1) == find(k2))
				cout<<"yes"<<endl;
			else cout<<"no"<<endl;
		}
	}
	return 0;

}

 

posted @ 2019-02-10 12:51  月光下の魔术师  阅读(3)  评论(0)    收藏  举报