hdu 5326 Work(并查集)

来源:互联网 发布:c语言设计 谭浩强pdf 编辑:程序博客网 时间:2024/05/22 03:35
                                                                                    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
输入的第一行:第一个数字n表示的是有几个人,第二个数字m表示查找管理两个人的。
       接下去就有n-1行表示前面的管理后面的,最后求的就是有几个人是管理m个人的
#include <stdio.h>#include<iostream>#include<algorithm>using namespace std;int map[110][110], p[110];int num[110],n,k;int find(int x){  while(p[x]!=x)  x=p[x];  return x;}void mange(int x, int y){    int a, b;    a = find(x);    b = find(y); if(a!=b) p[b] = a;}int main(){    while(~scanf("%d%d",&n,&k))    {        memset(map, 0, sizeof(map));        memset(num, 0, sizeof(num));        for (int i = 1; i<=n; i++)            p[i] = i;     int x, y;        for (int i = 1; i<n; i++)        {            scanf("%d%d",&x,&y);            mange(x,y);            map[x][y] = 1;//将其关系转换成图来储存        }        for (int i=1; i<=n;i++)        for (int j=1; j<=n;j++)        for (int k=1; k<=n;k++)        {        if (map[j][i] == 1 && map[i][k] == 1)        {        map[j][k] = 1;        }//关系之间的传递        }        for (int i = 1; i <= n; i++)        {            for (int j = 1; j <= n; j++)            {                if (p[j] == p[i] && i != j && map[i][j] == 1)                    num[i]++;//统计管理人数            }        }      int ans = 0;        for (int i=1; i<=n; i++)            if (num[i]==k) ans++;   printf("%d\n", ans);    }}


0 0
原创粉丝点击