HDU 4607 - Park Visit

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 \le 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 \le N,M \le 10^5)\), 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 \le K \le 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

Resume

在给定的边权值为1的树上,求出遍历M个点的最短路径。

Analysis

注意观察这棵树的特点——边权值为1。那么我们想要用最短的路径去走完这些点,就要尽量不走回头路,也就是说我们需要找出树上最长的链——树的直径
那么当要参观的点的数量K不多于直径所含点数D时,答案就是\(K-1\)
而当\(K \gt D\)时,我们需要参观直径之外的点,既然要去,就要回来,所以每额外参观一个点,就要多走2的距离,也就是说答案应该为 \(D - 1 + 2*(K-D) = 2*K - 1 - D\)

Code

//////////////////////////////////////////////////////////////////////
//Target: HDU 4607 - Park Visit
//@Author: Pisceskkk
//Date: 2019-2-21
//////////////////////////////////////////////////////////////////////

#include<cstdio>
#include<cstring>
#define N (int)1e5+10
using namespace std;

int t,n,m;
int q[N],d[N];
int he[N];

struct edge{
    int to,ne;
}e[N<<1];

void add_2(int x,int y,int i){
    i<<=1;
    e[i].ne = he[x];
    he[x] = i;
    e[i].to = y;
    i++;
    e[i].ne = he[y];
    he[y] = i;
    e[i].to = x;
}

int bfs(int s){
    int h=0,t=0;
    memset(d,0,sizeof(d));
    memset(q,0,sizeof(q));
    q[h++]=s;
    d[s] = 1;
    while(t<h){
        int x=q[t++],y;
        for(int i=he[x];i;i=e[i].ne){
            y = e[i].to;
            if(!d[y]){
                d[y] = d[x]+1;
                q[h++]=y;
            }
        }
    }
    return q[t-1];
}

int main(){
    scanf("%d",&t);
    while(t--){
        memset(e,0,sizeof(e));
        memset(he,0,sizeof(he));
        scanf("%d %d",&n,&m);
        int x,y;
        for(int i=1;i<n;i++){
            scanf("%d %d",&x,&y);
            add_2(x,y,i);
        }
        x = d[bfs(bfs(1))];
        while(m--){
            scanf("%d",&y);
            if(y<=x){
                printf("%d\n",y-1);
            }
            else {
                printf("%d\n",x + (y-x)*2 -1);
            }
        }
    }

}

猜你喜欢

转载自www.cnblogs.com/pisceskkk/p/10423177.html
今日推荐