Park Visit

来源:互联网 发布:京东为什么比淘宝贵 编辑:程序博客网 时间:2024/04/28 21:06

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≤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≤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

14 23 21 24 224
 

Sample Output

14
 

搜索题:灵活运用DFS活着BFS就能简单的搞定。
代码:
#include <algorithm>#include <iostream>#include <cstring>#include <cstdlib>#include <vector>#include <queue>#include <cstdio>#include <cmath>#include <string>#include <stack>#include <cctype>#define M 100005using namespace std;int n,m,kk,a[M],b[M];struct nod{    int to;    int nxt;} str[M*2];void add(int u,int v){    str[kk].to=v;    str[kk].nxt=a[u];    a[u]=kk++;}void DFS(int u){    for(int i=a[u]; i!=-1; i=str[i].nxt)    {        int v=str[i].to;        if(b[v]==-1)        {            b[v]=b[u]+1;            DFS(v);        }    }}int main(){    int t;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&n,&m);        kk=0;        memset(a,-1,sizeof(a));        int u,v;        for(int i=1; i<n; i++)        {            scanf("%d%d",&u,&v);            add(u,v);            add(v,u);        }        memset(b,-1,sizeof(b));        b[1]=0;        DFS(1);        int L=0;        for(int i=1; i<=n; i++)            if(b[i]>L)            {                L=b[i];                u=i;            }                    memset(b,-1,sizeof(b));        b[u]=0;        DFS(u);        L=0;        for(int i=1; i<=n; i++)            if(b[i]>L)                L=b[i];        L++;                int k;        while(m--)        {            scanf("%d",&k);            if(L>=k)                printf("%d\n",k-1);            else                printf("%d\n",(L-1)+(k-L)*2);        }    }    return 0;}




原创粉丝点击