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
1 4 2 3 2 1 2 4 2 2 4
Sample Output
1 4
求出树的直径,长度小于等于树的直径,就是可以直接走到的,否则,就得要多绕一倍。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN = 1e5 + 7;
int N, M, cnt, head[maxN];
ll dis[maxN];
struct Eddge
{
int nex, to;
Eddge(int a=-1, int b=0, ll c=0):nex(a), to(b) {}
}edge[maxN<<1];
void addEddge(int u, int v)
{
edge[cnt] = Eddge(head[u], v);
head[u] = cnt++;
}
int large_dis, its_pos;
int L, R; //最后得到的树的直径的两头的点
void dfs1(int u, int fa, int juli)
{
if(juli > large_dis)
{
large_dis = juli;
its_pos = u;
}
for(int i=head[u]; i!=-1; i=edge[i].nex)
{
int v = edge[i].to;
if(v == fa) continue;
dfs1(v, u, juli + 1);
}
}
void dfs2(int u, int fa, int juli)
{
if(juli > large_dis)
{
large_dis = juli;
R = u;
}
for(int i=head[u]; i!=-1; i=edge[i].nex)
{
int v = edge[i].to;
if(v == fa) continue;
dfs2(v, u, juli + 1);
}
}
void solve_RD_of_Tree()
{
large_dis = 0;
dfs1(1, 1, 0);
L = its_pos;
large_dis = 0;
dfs2(L, L, 0);
}
void init()
{
cnt = 0;
memset(dis, 0, sizeof(dis));
memset(head, -1, sizeof(head));
}
int main()
{
int T; scanf("%d", &T);
while(T--)
{
scanf("%d%d", &N, &M);
init();
for(int i=2; i<=N; i++)
{
int e1, e2;
scanf("%d%d", &e1, &e2);
addEddge(e1, e2);
addEddge(e2, e1);
}
solve_RD_of_Tree();
large_dis++;
while(M--)
{
int e1;
scanf("%d", &e1);
if(e1<=large_dis) printf("%d\n", e1 - 1);
else
{
int det = e1 - large_dis;
printf("%d\n", det*2 + large_dis - 1);
}
}
}
return 0;
}