hdu 5326(Work)

来源:互联网 发布:linux获取线程优先级 编辑:程序博客网 时间:2024/06/05 11:06

Work  (并查集)

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

题意:给出管理员和员工的编号,问有多少领导管理了两个人。

题解:对于每组输入,直接把a设为b的父节点,不需要Union()函数。

代码:

#include<cstdio>using namespace std;int n;int fa[110];int rank[110];void init(){for (int i=1;i<=n;i++){fa[i]=i;rank[i]=0;}}int find(int x){while (x!=fa[x]){rank[fa[x]]++;x=fa[x];}}int main(){int k;int a,b,sum;while (scanf ("%d %d",&n,&k)!=EOF){sum=0;init();for (int i=1;i<n;i++){scanf ("%d %d",&a,&b);fa[b]=a;}for (int i=1;i<=n;i++){//遍历每一个节点 ,刚开始wa在这里,因为只find(a)了find(i);}for (int i=1;i<=n;i++){if (rank[i]==k)sum++;}printf ("%d\n",sum);}return 0;}


0 0
原创粉丝点击