1118. Birds in Forest (25)

快来打我* 2022-05-28 13:14 222阅读 0赞

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:

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

Sample Output:

  1. 2 10
  2. Yes
  3. No

题目大意:

代码:

  1. #include<stdio.h>
  2. int F[10001];
  3. int visited[10001];
  4. int cnt[10001];
  5. int find(int x) {
  6. int a = x;
  7. while(x != F[x])
  8. x = F[x];
  9. while(a != F[a]) {
  10. int z = a;
  11. a = F[a];
  12. F[z] = x;
  13. }
  14. return x;
  15. }
  16. void Union(int x,int y)
  17. {
  18. int fx=find(x);
  19. int fy=find(y);
  20. if(fx!=fy)
  21. {
  22. F[fx]=fy;
  23. }
  24. }
  25. int main()
  26. {
  27. int i,j,n,m,k,t,first,numtree=0,numbird=0,bird1,bird2;
  28. for(i=1;i<=10000;i++)
  29. F[i]=i;
  30. scanf("%d",&n);
  31. for(i=0;i<n;i++)
  32. {
  33. scanf("%d %d",&m,&first);
  34. visited[first]=1;
  35. for(j=1;j<m;j++)
  36. {
  37. scanf("%d",&k);
  38. Union(first,k);
  39. visited[k]=1;
  40. }
  41. }
  42. for(i=1;i<=10000;i++)
  43. {
  44. if(visited[i]==1)
  45. {
  46. int root=find(i);
  47. cnt[root]++;
  48. }
  49. }
  50. for(i=1;i<=10000;i++)
  51. {
  52. if(cnt[i]!=0)
  53. {
  54. numtree++;
  55. numbird+=cnt[i];
  56. }
  57. }
  58. printf("%d %d\n",numtree,numbird);
  59. scanf("%d",&t);
  60. for(i=0;i<t;i++)
  61. {
  62. scanf("%d %d",&bird1,&bird2);
  63. if(find(bird1)==find(bird2))
  64. {
  65. printf("Yes\n");
  66. }
  67. else
  68. {
  69. printf("No\n");
  70. }
  71. }
  72. return 0;
  73. }

发表评论

表情:
评论列表 (有 0 条评论,222人围观)

还没有评论,来说两句吧...

相关阅读

    相关 1118 day4

    1.简述GBDT原u理。 首先根据现有的数据训练树一棵树,然后去计算真实值和预测值的差值,也就是残差,然后下一棵树去拟合该残差,重复直至残差为0。 所有弱分类器的结果相加等

    相关 Forest介绍

    前言 本篇栏目主要和大家分享我对国内一款开源框架Forest的一些研究学习文章。 如果大家也在对他感兴趣,并且对他底层实现有一定的好奇,希望我的这个栏目文章可以给到大家