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;
}