并查集:HDU5326-Work(并查集比较简单灵活的运用)

Work

HDU原题地址:http://acm.hdu.edu.cn/showproblem.php?pid=5326
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2109 Accepted Submission(s): 1236**
这里写图片描述

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 2
1 2
1 3
2 4
2 5
3 6
3 7

Sample Output

2


解题心得
- 这个题不难,但是容易受并查集的思维的影响,不能够太固化,对于新手来说是很好的一个并查集的应用,思维不能固化啊,不然要折腾好半天,代码很容易看明白还是看代码吧。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 110;
int father[maxn],sum[maxn];
int n,m,ans;

int find(int x)
{
    int r;
    int k = x;
    while(k != father[k])
    {
        r = father[k];
        k = r;
        sum[r]++;//前面的根找的一个则加一,很简单,
    }
}

void merge(int a,int b)
{
    father[b] = a;
}

int main()
{
    while(scanf("%d%d",&n,&m) != EOF)
    {
        ans = 0;
        memset(sum,0,sizeof(sum));
        for(int i=0; i<=n+1; i++)
            father[i] = i;
        int N = n-1;
        while(N--)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            if(a != b)//这里不用判断是否是同一根,直接建立关系就行了
            {
                merge(a,b);//先合并
                find(b);//逐层上找,直到找到最前的那个根
            }
        }
        for(int i=1;i<=n;i++)
            if(sum[i] == m)
                ans++;
        printf("%d
",ans);
    }
}
原文地址:https://www.cnblogs.com/GoldenFingers/p/9107319.html