1066 无间道之并查集并查集 解题报告

1.这一题解题注意点在于:

1)基本的数据算法当然是并查集+注意路劲的压缩,路径的压缩也很简单,即路径上的各个节点都知向根节点;

2)需要将名字映射成id,便于并查集的表示,采用map容器可以很好的做到这一点;

上代码:

#include<iostream>
#include<string>
#include<map>
#include<fstream>
using namespace std;


//#define cin in

int pre[200005];//indicate the pre of the node

void init()
{
	for (int i = 0; i < 200005; i++)
		pre[i] = i;
}

int find(int x){
	int r = x;
	
	while (r != pre[r])r = pre[r];//寻找父节点
	//路径压缩

	while (x != r)
	{
		int j = pre[x];
		pre[x] = r;
		x = j;
	}
	return r;
}
void unite(int x, int y)
{
	int px = find(x);
	int py = find(y);
	if (px < py)
		pre[py] = pre[px];
	else if(px > py)
		pre[px] = pre[py];
}


int main()
{
//	fstream in("1.txt");
	int n;
	cin >> n;
	int cnt = 0;
	init();



	map < string, int> name2id;
	while (n--)
	{
		int oper;
		string s1, s2;
		cin >> oper >> s1 >> s2;
		if (!name2id.count(s1))
			name2id.insert(make_pair(s1, cnt++));
		if (!name2id.count(s2))
			name2id.insert(make_pair(s2, cnt++));
		
		if (oper == 0)
			unite(name2id[s1], name2id[s2]);
		else{
			if (find(name2id[s1]) == find(name2id[s2]))
				cout << "yes" << endl; 
			else
				cout << "no" << endl;
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值