码迷,mamicode.com
首页 > 其他好文 > 详细

ACM学习历程—HDU 5326 Work(树形递推)

时间:2015-07-28 20:42:38      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

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

这个题目是个递推,不过由于是树形的,需要dfs来完成递推的过程。

关键在于p[now] += p[to]+1;如果now能manage to的话。

此处采用链式前向星来保存关系图。

 

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <algorithm>
#define LL long long

using namespace std;

const int maxN = 105;

struct Edge
{
    int to, next;
}edge[maxN];

int head[maxN], cnt;

void addEdge(int u, int v)
{
    edge[cnt].to = v;
    edge[cnt].next = head[u];
    head[u] = cnt;
    cnt++;
}

void initEdge()
{
    memset(head, -1, sizeof(head));
    cnt = 0;
}

int n, k;
int fa[maxN], p[maxN];

void input()
{
    initEdge();
    memset(p, -1, sizeof(p));
    int u, v;
    for (int i = 1; i < n; ++i)
    {
        scanf("%d%d", &u, &v);
        addEdge(u, v);
    }
}


void dfs(int now)
{
    p[now] = 0;
    int to;
    for (int i = head[now]; i != -1; i = edge[i].next)
    {
        to = edge[i].to;
        if (p[to] == -1)
            dfs(to);
        p[now] += p[to]+1;
    }
}

void work()
{
    int ans = 0;
    for (int i = 1; i <= n; ++i)
    {
        if (p[i] != -1)
        {
            if (p[i] == k)
                ans++;
        }
        else
        {
            dfs(i);
            if (p[i] == k)
                ans++;
        }
    }
    printf("%d\n", ans);
}

int main()
{
    //freopen("test.in", "r", stdin);
    while (scanf("%d%d", &n, &k) != EOF)
    {
        input();
        work();
    }
    return 0;
}

 

ACM学习历程—HDU 5326 Work(树形递推)

标签:

原文地址:http://www.cnblogs.com/andyqsmart/p/4684192.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!