2015
09-17

Park Visit

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?

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.

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.

1
4 2
3 2
1 2
4 2
2
4

1
4

/***************************************************

N个点和N-1条边,保证整个图连通(因为边的限制,所以不可能形成环);

****************************************************/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int N=100005;
const int INF=0xffffff;

int n,m,k;
struct Edges
{
int v,next;
} edge[N*2];

int e;
int q[N],vis[N],d[N];

{
edge[e].v=v;
}

void bfs(int src)
{
for(int i = 1; i <= n; i++)
{
vis[i]=0;
d[i] = INF;
}
int h=0,t=0;//队列头尾
q[t++]=src;
vis[src]=1;
d[src]=0;
while(h<t)
{
int u = q[h++];
for(int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].v;
if(d[u]+1<d[v])
{
d[v]= d[u]+1;
if(!vis[v])
{
q[t++]=v;
vis[v]=1;
}
}
}
}
}

int main()
{
int tcase;
scanf("%d",&tcase);
while(tcase--)
{
int u,v;
scanf("%d%d", &n, &m);
e=0;
for(int i=1; i<n; i++)
{
scanf("%d%d",&u,&v);
}

bfs(1);

int pos=-1;
int x=-1;
for(int i=1; i<=n; i++)
if(d[i]>x)
{
x=d[i];
pos=i;
}

bfs(pos);

x=-1;
for(int i=1; i<=n; i++)
{
if(d[i]>x)
x=d[i];
}
for(int i=0; i<m; i++)
{
scanf("%d",&k);
if(k<=x+1)
printf("%d\n", k-1);
else
printf("%d\n",x+2*(k-x-1));
}
}
return 0;
}