A1118 Birds in Forest (25 point(s))

并查集的应用

1. 原文

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 (≤10^4) which is the number of pictures. Then N lines follow, each describes a picture in the format:

K B1 B2 … BK

where K is the number of birds in this picture, and Bi‘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 10^4.

After the pictures there is a positive number Q (≤10^4) 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:

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

Sample output:

1
2
3
2 10
Yes
No

2. 解析

并查集固定套路

father[]初始化为指向自己father[i]=i

查找指向,不同时指向其中一个

set记录结点

map统计结点父结点个数

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include<cstdio>
#include<set>
#include<map>
using namespace std;
const int maxn=10010;
set<int> v;
map<int,int> isroot;
int father[maxn]={};
void init()
{
for (int i = 1; i < maxn; ++i)
{
father[i]=i;
}
}
int findFather(int x){
int a=x;
while(x!=father[x]){
x=father[x];
}
while(a!=father[a]){
int z=a;
a=father[a];
father[z]=x;
}
return x;
}
void together(int a,int b){
int fatherA=findFather(a);
int fatherB=findFather(b);
if (fatherB!=fatherA)
{
father[fatherA]=fatherB;
}
}
int main()
{
init();
int n;
scanf("%d",&n);
while(n--)
{
int k,a;
scanf("%d%d",&k,&a);
v.insert(a);
int b;
for (int i = 1; i < k; ++i)
{
scanf("%d",&b);
v.insert(b);
together(a,b);
a=b;
}
}
for (set<int>::iterator i = v.begin(); i != v.end(); ++i)
{
isroot[findFather(*i)]++;
}
printf("%lu %lu\n", isroot.size(),v.size());
int q;
scanf("%d",&q);
int a,b;
for (int i = 0; i < q; ++i)
{
scanf("%d%d",&a,&b);
if (father[a]==father[b])
{
printf("Yes\n");
}else{
printf("No\n");
}
}

return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1118/
  • 发布时间: 2019-09-03 12:29
  • 更新时间: 2021-10-29 14:08
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!