1. 程式人生 > >PAT甲級——1118 Birds in Forest (並查集)

PAT甲級——1118 Birds in Forest (並查集)

his HERE tex 大數組 照片 style oss rom printf

此文章 同步發布在CSDN:https://blog.csdn.net/weixin_44385565/article/details/89819984 1118 Birds in Forest (25 分)

Some scientists took pictures of thousands of birds in a forest. Assume that all the birds appear in the same picture belong to the same tree. You are supposed to help the scientists to count the maximum number of trees in the forest, and for any pair of birds, tell if they are on the same tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive number N (≤) which is the number of pictures. Then N lines follow, each describes a picture in the format:

K B?1?? B?2?? ... B?K??

where K is the number of birds in this picture, and B?i??‘s are the indices of birds. It is guaranteed that the birds in all the pictures are numbered continuously from 1 to some number that is no more than 1.

After the pictures there is a positive number Q (≤) which is the number of queries. Then Q lines follow, each contains the indices of two birds.

Output Specification:

For each test case, first output in a line the maximum possible number of trees and the number of birds. Then for each query, print in a line Yes

if the two birds belong to the same tree, or No if not.

Sample Input:

4
3 10 1 2
2 3 4
4 1 5 7 8
3 9 6 4
2
10 5
3 7

Sample Output:

2 10
Yes
No

題目大意: 有N張照片,每張照片裏面有K只鳥,它們屬於同一棵樹,每只鳥從1開始連續編號。接著有Q條查詢指令,每條指令包含兩只鳥的編號;要求先輸出樹的數量和鳥的數量,再對每條查詢指令判斷這兩只鳥是否屬於同一棵樹。

思路:並查集的操作沒啥好說的,略過~~,定義一個大數組S作為集合,並將所有元素初始化為-1;由於鳥的編號是連續的,那麽最大的那個編號就是鳥的數量,同時也是集合S的size,遍歷集合S,S中小於0的元素的數量就是樹的數量。

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 int findRoot(int X);//尋找樹的根
 5 void unionSet(int root, int Y);
 6 vector <int> S(10001, -1);//將集合元素初始化為-1
 7 int main()
 8 {
 9     int N, setSize = 0, Q, treeNum = 0;
10     scanf("%d", &N);
11     for (int i = 0; i < N; i++) {
12         int K, B, root;
13         scanf("%d%d", &K, &B);
14         root = findRoot(B);
15         if (setSize < B) setSize = B;
16         for (int j = 1; j < K; j++) {
17             scanf("%d", &B);
18             if (setSize < B) setSize = B;
19             unionSet(root, B);
20         }
21     }
22     for (int i = 1; i <= setSize; i++) 
23         if (S[i] < 0) 
24             treeNum++;
25     printf("%d %d\n", treeNum, setSize);
26     scanf("%d", &Q);
27     for (int i = 0; i < Q; i++) {
28         int X, Y;
29         scanf("%d%d", &X, &Y);
30         printf(findRoot(X) == findRoot(Y) ? "Yes\n" : "No\n");
31     }
32 }
33 void unionSet(int root, int Y) {
34     int rootY = findRoot(Y);
35     S[rootY] = root;
36 }
37 int findRoot(int X) {
38     if (S[X] < 0) {
39         return X;
40     }
41     else {
42         return S[X] = findRoot(S[X]);//遞歸地進行路徑壓縮
43     }
44 }

PAT甲級——1118 Birds in Forest (並查集)