您的位置:首页 > 编程语言 > C语言/C++

1118. Birds in Forest

2016-09-13 18:55 387 查看


1118. Birds in Forest (25)

时间限制

150 ms

内存限制

65536 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

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
考试的时候这题两个点超时,原因是我用set把每个树的子节点都存了起来,并查集合并的时候,又把set合并,有点蠢。。。
这次就是把所有鸟的树标号记录了一下,对比标号的根即可。
树的数量就是合并后根仍为自己的节点的个数,鸟的数量,记一下有标号的鸟数量即可。
#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

const int NMAX=10001;
typedef struct picture
{
int root;
vector<int>b;
};
picture p[NMAX];
int bird[NMAX];

int findr(int num)
{
if(p[num].root==num)
return num;
int r=findr(p[num].root);
p[num].root=r;
return r;
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=10000;i++)
bird[i]=-1;
for(int i=0;i<n;i++)
{
p[i].root=i;
int k;
cin>>k;
for(int j=0;j<k;j++)
{
int b;
cin>>b;
p[i].b.push_back(b);
bird[b]=i;
}
}
for(int i=0;i<n;i++)
{
int r1=findr(i);
for(int j=0;j<p[i].b.size();j++)
{
int r2=findr(bird[p[i].b[j]]);
if(r1!=bi
4000
rd[p[i].b[j]])
{
bird[p[i].b[j]]=r1;
p[r2].root=r1;
}
}
}
int cnt=0,num=0;
for(int i=0;i<n;i++)
if(p[i].root==i)
cnt++;
for(int i=1;i<=10000;i++)
{
if(bird[i]!=-1)
num++;
}
cout<<cnt<<" "<<num<<endl;
int q;
cin>>q;
for(int i=0;i<q;i++)
{
int b1,b2;
cin>>b1>>b2;
if(findr(bird[b1])==findr(bird[b2]))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PAT C++