最开始用的HASH的方法,发现有问题。
这里会出现的问题主要是当出现3段的时候,例如:
① 1 2 3
② 4 5 6
③ 3 7 4
的时候Hash会误将这个当成两棵树,而出现问题。
不出现问题的方法估计也有,但是感觉没有直接用并查集方便。
#include <iostream>
#include <vector>
#include <cstring>
#define MAX 10010
using namespace std;
struct Node {
int bird;
int father;
};
vector <Node> p;
int n;
vector <int> picture;
int TreeCount[MAX];//用于统计树的数目
void InitSet(int BirdNum) {//初始化并查集
p.resize(BirdNum);
for (int i = 0; i < BirdNum; i++) {
p[i].father = i;
p[i].bird = 0;
}
}
void Compress(int top, int x) {//压缩路径
if (top != p[x].father) {
Compress(top, p[x].father);
p[x].father = top;
}
}
int FindSet(int x) {
if (x != p[x].father) {
int top = FindSet(p[x].father);
Compress(top, x);
}
return p[x].father;
}
void Union(int x, int y) {
int a = FindSet(x);
int b = FindSet(y);
p[a].father = b;
}
int main() {
InitSet(MAX);
int max = 0;
int Tree = 0;
cin >> n;
for (int i = 0; i < n; i++) {
int BirdNum;
int firstBird;
int Bird;
cin >> BirdNum;
for (int j = 0; j < BirdNum; j++) {
cin >> Bird;
if (Bird > max)
max = Bird;
if (j == 0) {
firstBird = Bird;
continue;
}
Union(firstBird, Bird);
}
}
memset(TreeCount, 0, sizeof(TreeCount));
for (int i = 1; i <= max; i++) {
int father = FindSet(i);
TreeCount[father]++;
if (TreeCount[father] == 1) Tree++;
}
cout << Tree << " " << max << endl;
int m;
cin >> m;
for (int i = 0; i < m; i++) {
int b1, b2;
cin >> b1 >> b2;
// cout << FindSet(b1) << " " << FindSet(b2) << endl;
if (FindSet(b1) == FindSet(b2))
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}