HDOJ 5326 Work(类似并查集)

来源:互联网 发布:我要复仇知乎 编辑:程序博客网 时间:2024/06/06 00:10

Work

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1781    Accepted Submission(s): 1065


Problem Description


It’s an interesting experience to move from ICPC to work, end my college life and start a brand new journey in company.
As is known to all, every stuff in a company has a title, everyone except the boss has a direct leader, and all the relationship forms a tree. If A’s title is higher than B(A is the direct or indirect leader of B), we call it A manages B.
Now, give you the relation of a company, can you calculate how many people manage k people.
 

Input
There are multiple test cases.
Each test case begins with two integers n and k, n indicates the number of stuff of the company.
Each of the following n-1 lines has two integers A and B, means A is the direct leader of B.

1 <= n <= 100 , 0 <= k < n
1 <= A, B <= n
 

Output
For each test case, output the answer as described above.
 

Sample Input
7 21 21 32 42 53 63 7
 

Sample Output
2
 

Author
ZSTU
 

Source
2015 Multi-University Training Contest 3 

思路:
题意就是,给了你每组a,b代表a是b的祖先,且具有传递性,那么问你有几个人,它的儿子个数是m。思想就是类似于并查集找祖先的思想,对于每个点,都去找它的祖先路径,并且没经过一个点那么这个点的父亲数++并且经过的点的儿子数++,直到遇到一个点它的祖先是它自己为止。然后对这些数遍历,就得到了每个点的父亲数和儿子数。


代码:
#include<iostream>#include<stdio.h>#include<cstring> using namespace std; int ancestor[1001];  //储存祖先 int son[10014];  //储存儿子         void find(int p)  {      while(p!=ancestor[p])      {           p=ancestor[p];           son[p]++;      }   }  int main()  {      int n,a,b,m;      while(scanf("%d%d",&n,&m)!=EOF)      {          for(int i=1;i<=n;i++)          {              ancestor[i]=i;              son[i]=0;          }          for(int i=1;i<n;i++)         {              scanf("%d%d",&a,&b);              ancestor[b]=a;          }          int sum=0;          for(int i=1;i<=n;i++)          {              find(i);          }         for(int i=1;i<=n;i++)         {              if(son[i]==m)              sum++;         }              printf("%d\n",sum);      }      return 0;  }  
0 0