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 (<= 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 7Sample Output:
2 10 Yes No
题意:每张照片都若干只鸟,同一张照片上的鸟算作是同一棵树上的鸟。问有几棵树,几只鸟。再问给的两只鸟是不是属于同一棵树
思路:并查集。
注:找集合根 的函数需要压缩路径,不然有一个点过不去
AC代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
int book[10010]={0};
int father[10010];
void init(int n)
{
int i;
for(i=1;i<=n;i++)
{
father[i]=i;
}
}
int findRoot(int x)//找到根
{
int root=x;
while(root!=father[root])
root=father[root];
//路径压缩
while(x!=father[x])
{
int t=x;
x=father[x];
father[t]=root;
}
return root;
}
void Union(int a,int b)//合并a b所在的集合。通过集合的root来合并
{
int roota=findRoot(a);
int rootb=findRoot(b);
father[roota]=rootb;
}
int main()
{
//freopen("in.txt","r",stdin);
int N,max1=0;
cin>>N;
init(N);
for(int i=1;i<=N;i++)
{
int k;
cin>>k;
for(int j=1;j<=k;j++)
{
int b;
cin>>b;
if(b>max1)
max1=b;
if(book[b]==0)
{
book[b]=i;
}
else
{
Union(i,book[b]);
}
}
}
int cou1=0;
for(int i=1;i<=N;i++)
{
if(father[i]==i)
cou1++;
}
printf("%d %d\n",cou1,max1);
int Q;
cin>>Q;
while(Q--)
{
int t1,t2;
cin>>t1>>t2;
if(findRoot(book[t1])==findRoot(book[t2]))
printf("Yes\n");
else
printf("No\n");
}
/*
for(int i=1;i<=N;i++)
{
printf("%d -> %d\n",i,father[i]);
}
*/
return 0;
}
385

被折叠的 条评论
为什么被折叠?



