首页 > 其他 > 详细

HDU 4607 Park Visit

时间:2015-05-27 08:30:30      阅读:302      评论:0      收藏:0      [点我收藏+]

Problem Description

Claire and her little friend, ykwd, are travelling in Shevchenko‘s Park! The park is beautiful - but large, indeed. N feature spots in the park are connected by exactly (N-1) undirected paths, and Claire is too tired to visit all of them. After consideration, she decides to visit only K spots among them. She takes out a map of the park, and luckily, finds that there‘re entrances at each feature spot! Claire wants to choose an entrance, and find a way of visit to minimize the distance she has to walk. For convenience, we can assume the length of all paths are 1.
Claire is too tired. Can you help her?

Input

An integer T(T≤20) will exist in the first line of input, indicating the number of test cases.
Each test case begins with two integers N and M(1≤N,M≤105), which respectively denotes the number of nodes and queries.
The following (N-1) lines, each with a pair of integers (u,v), describe the tree edges.
The following M lines, each with an integer K(1≤K≤N), describe the queries.
The nodes are labeled from 1 to N.

Output

For each query, output the minimum walking distance, one per line.

Sample Input

1 4 2 3 2 1 2 4 2 2 4

Sample Output

1 4
 
题解:先求出树的直径,假设为ans,若k <= m,那么最短距离为(k - 1);否则最短距离为((k - m) * 2 + m - 1);
CODE:
#include <iostream>
#include <cstdio>
#include <cstring>
#define REP(i, s, n) for(int i = s; i <= n; i ++)
#define REP_(i, s, n) for(int i = n; i >= s; i --)
#define MAX_N 100000 + 10

using namespace std;

int n, m, head[MAX_N], top = 0, mx, ans = 0;
struct node{
    int v, next;
}E[MAX_N << 1];
bool used[MAX_N];

void add(int u, int v){
    E[++ top].v = v; E[top].next = head[u]; head[u] = top;
}

void dfs(int d, int x){
    used[x] = 0;
    if(d > ans) ans = d, mx = x;
    for(int i = head[x]; i; i = E[i].next){
        if(used[E[i].v]) dfs(d + 1, E[i].v);
    }
    used[x] = 1;
}

int main(){
    int T; scanf("%d", &T);
    while(T --){
        int u, v, q; top = 0;
        memset(used, 1, sizeof(used)); memset(head, 0, sizeof(head));
        scanf("%d%d", &n, &m);
        REP(i, 1, n - 1){
            scanf("%d%d", &u, &v); 
            add(u, v); add(v, u);
        }

        ans = 0;
        dfs(0, 1); dfs(0, mx); ans ++;

        while(m -- ){ 
            scanf("%d", &q);
            if(q <= ans) printf("%d\n", q - 1);
            else printf("%d\n", (q - ans) * 2 + ans - 1);
        }
    }
    return 0;
}

 

HDU 4607 Park Visit

原文:http://www.cnblogs.com/ALXPCUN/p/4532386.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!