单词积累
assume 假定 设想
indices index的复数形式 指针 指数
题目
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 (≤104) 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 104.
After the pictures there is a positive number Q (≤104) 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
结尾无空行
思路
典型的并查集应用,处理麻烦倒还好说,样例一直过不去,花了好长时间看,结果是输出的yes和no的大小写问题,太粗心了呀,真是大教训。
此外,本题还需要用到路径压缩,否则会时间超限。此处学到了非常简洁的递归写法,非常优美。
代码
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
int father[maxn];
int visit[maxn];
int numbers[maxn];
void inital() {
for (int i = 0; i < maxn; i++) {
father[i] = i;
visit[i] = 0;
numbers[i] = 0;
}
}
int findfather(int x) {
if (x != father[x]) {
father[x] = findfather(father[x]);
}
return father[x];
}
void Union(int a, int b) {
visit[a] = 1;
visit[b] = 1;
int x = findfather(a);
int y = findfather(b);
if (x == y) return;
else {
father[y] = x;
}
}
int main() {
int N;
inital();
cin>>N;
int k;
for (int i = 0; i < N; i++) {
int birds[10001];
cin>>k;
for (int j = 0; j < k; j++) {
cin>>birds[j];
Union(birds[0],birds[j]);
}
}
for (int i = 1; i < maxn; i++) {
if (visit[i] == 1) {
int root = findfather(i);
numbers[root]++;
}
}
int trees = 0;
int allbird = 0;
for (int i = 1; i < maxn; i++) {
if (visit[i] == 1 && numbers[i] != 0) {
trees++;
allbird += numbers[i];
}
}
cout<<trees<<" "<<allbird<<endl;
int Q, q1, q2;
cin>>Q;
for (int i = 0; i < Q; i++) {
cin>>q1>>q2;
int x = findfather(q1);
int y = findfather(q2);
if (x == y) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}