在一个社区里,每个人都有自己的小圈子,还可能同时属于很多不同的朋友圈。我们认为朋友的朋友都算在一个部落里,于是要请你统计一下,在一个给定社区中,到底有多少个互不相交的部落?并且检查任意两个人是否属于同一个部落。
输入格式:
输入在第一行给出一个正整数N(≤10^4),是已知小圈子的个数。随后N行,每行按下列格式给出一个小圈子里的人:
K P[1] P[2] ⋯ P[K]
其中K是小圈子里的人数,P[i](i=1,⋯,K)是小圈子里每个人的编号。这里所有人的编号从1开始连续编号,最大编号不会超过10^4。
之后一行给出一个非负整数Q(≤10^4),是查询次数。随后Q行,每行给出一对被查询的人的编号。
输出格式:
首先在一行中输出这个社区的总人数、以及互不相交的部落的个数。随后对每一次查询,如果他们属于同一个部落,则在一行中输出Y,否则输出N。
输入样例:
4
3 10 1 2
2 3 4
4 1 5 7 8
3 9 6 4
2
10 5
3 7输出样例:
10 2
Y
N
#include <iostream>
#include <map>
#include <algorithm>
#include <set>
#define MAXSIZE 10010
using namespace std;
map<int, int> anc;
int findd(int x)
{
if (anc[x] == x)
return x;
anc[x] = findd(anc[x]);
return anc[x];
}
void unionn(int a, int b)
{
int a_anc = findd(a);
int b_anc = findd(b);
anc[a_anc] = b_anc;
return;
}
int main()
{
int n, temp, k, q; cin >> n;
set<int> per; //不同的人
set<int> ancs; //不同的共同祖先
for (int i = 0; i < n; i++) {
cin >> k;
if (k == 1) {
cin >> temp; per.insert(temp);
anc.insert(make_pair(temp, temp));
}
else {
int pe;
cin >> pe; per.insert(pe);
anc.insert(make_pair(pe, pe));
for (int j = 0; j < k - 1; j++) {
cin >> temp; per.insert(temp);
anc.insert(make_pair(temp, temp));
unionn(pe, temp);
}
}
}
for (int i = 1; i <= anc.size(); i++) {
findd(i); //更新共同祖先
}
for (map<int, int>::iterator it = anc.begin(); it != anc.end(); it++) {
ancs.insert((*it).second);
}
cout << per.size() << " " << ancs.size() << endl;
cin >> q;
for (int i = 0; i < q; i++) {
int a, b; cin >> a >> b;
if (anc[a] == anc[b]) cout << "Y" << endl;
else cout << "N" << endl;
}
return 0;
}
注意事项:
考虑使用并查集,同一个圈子的人建立联系。对于社区总人数和部落(祖先相同)总数,可以使用set容器,自带去重功能。在使用共同祖先前,需要用findd函数更新一下所有人的祖先,因为findd路径压缩只会更新一条线上的祖先,其分支的祖先不变。
如有问题,欢迎提出。