Time Limit: 3000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
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?
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.
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<cstring>
#include<string>
#include<queue>
#include<vector>
using namespace std;
const int MAXN = 200050; //邻接矩阵的实现
vector<int>g[MAXN];
int d[MAXN];
int n, m;
int BFS(int s) //深搜
{
queue<int> q; //先进先出的队列。
memset(d, -1, sizeof d); //d[u]数组为s到u点的距离,-1表示没搜过。
d[s] = 0; //搜索起点加入队列。
q.push(s);
while (!q.empty()) //队列非空。
{
int u = q.front(); //取出队头,搜索其下的点
q.pop();
for (int i = 0; i<g[u].size(); i++)
{
if (d[g[u][i]] == -1) //没搜过
{
d[g[u][i]] = d[u] + 1; //记录距离
q.push(g[u][i]); //加入队列
}
}
}
int max = d[1], sign = 1;
for (int i = 2; i <= n; ++i) //返回距离s距离最远的点
{
if (d[i] > max)
{
max = d[i];
sign = i;
}
}
return sign;
}
int main()
{
int casen;
cin >> casen;
while (casen--)
{
cin >> n>>m;
for (int i = 0; i <= n; i++)
g[i].clear();
int a, b;
for (int i = 1; i <= n-1; i++)
{
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
int u, v;
u = BFS(1);
v = BFS(u);
int D = d[v];
int k;
while (m--)
{
cin >> k;
if (k <= D) cout << k - 1 << endl;
else cout << (k - D - 1) * 2 + D << endl;
}
}
}