部落(PTA)

7-12 部落 (25 分)

在一个社区里,每个人都有自己的小圈子,还可能同时属于很多不同的朋友圈。我们认为朋友的朋友都算在一个部落里,于是要请你统计一下,在一个给定社区中,到底有多少个互不相交的部落?并且检查任意两个人是否属于同一个部落。

输入格式:

输入在第一行给出一个正整数N(104​​),是已知小圈子的个数。随后N行,每行按下列格式给出一个小圈子里的人:

K P[1] P[2] P[K]

其中K是小圈子里的人数,P[i](i=1,,K)是小圈子里每个人的编号。这里所有人的编号从1开始连续编号,最大编号不会超过104​​。

之后一行给出一个非负整数Q(104​​),是查询次数。随后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

并查集,以每组第1个为根,再优化一下found函数即可

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <set>
 4 #include <map>
 5 using namespace std;
 6 
 7 const int N=1e4+5;
 8 int root[N];
 9 set<int> st;
10 map<int,int> mp;
11 
12 int found(int x)
13 {
14     int k=x;
15     while(root[k]!=k){
16         k=root[k];
17     }
18     int w=x;
19     while(root[w]!=k){
20         int y=root[w];
21         root[w]=k;
22         w=y;
23     }
24     return k;
25 }
26 
27 int main()
28 {
29     int n,q,m,x,kr,t;
30     scanf("%d",&n);
31     for(int i=1;i<=1e4;i++){
32         root[i]=i;
33     }
34     for(int i=0;i<n;i++){
35         scanf("%d",&m);
36         for(int j=0;j<m;j++){
37             scanf("%d",&x);
38             mp[x]=1;
39             st.insert(x);
40             int fx=found(x);
41             if(j==0) kr=fx;
42             else{
43                 if(fx!=kr){
44                     root[fx]=kr;
45                 }
46             }
47         }
48     }
49     int sum=st.size(),cnt=0;
50     for(int i=1;i<=1e4;i++){
51         if(root[i]==i&&mp[i]==1){
52             cnt++;
53         }
54     }
55     cout<<sum<<" "<<cnt<<endl;
56     scanf("%d",&t);
57     int a,b;
58     for(int i=0;i<t;i++){
59         scanf("%d %d",&a,&b);
60         if(found(a)==found(b)){
61             cout<<"Y"<<endl;
62         }
63         else cout<<"N"<<endl;
64     }
65     return 0;
66 }
原文地址:https://www.cnblogs.com/ChangeG1824/p/10464804.html