数据结构算法(4)--并查集
数据结构算法(4)--并查集
并查集的使用
Note:
#include <iostream>
using namespace std;
int father[5001];
//寻找父节点
int find(int node)
{
if (father[node] == node)
return node;
return father[node] = find(father[node]);//路径压缩
}
//合并两个集合
void Union(int i, int j)
{
int p1 = find(i);
int p2 = find(j);
if (p1 != p2)
{
if (p1 < p2)//取值较小节点为父节点
{
father[p2] = p1;
}
else
{
father[p1] = p2;
}
}
}
//判断两个节点是否在同一集合中
bool Different(int i, int j)
{
int p1 = find(i);
int p2 = find(j);
if (p1 != p2)
return true;
else
return false;
}
int main()
{
int n, m, p;
cin >> n >> m >> p;
for (int i = 1; i <= n; ++i)
father[i] = i;
for (int i = 0; i < m; ++i)
{
int t1, t2;
cin >> t1 >> t2;
if(t1!=t2)
Union(t1, t2);
}
for (int i = 0; i < p; ++i)
{
int t1, t2;
cin >> t1 >> t2;
if (Different(t1, t2))
cout << "No" << endl;
else
cout << "Yes" << endl;
}
}