Park Visit
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4213 Accepted Submission(s): 1870
Problem 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
该题描述的是一颗树,要使得走K个点而所耗费的路程最小(每两个点之间的距离为1),则走树的直径即可。
若K<= 树的直径D,则耗费为K-1;
否则,耗费为D - 1 + (D - K) * 2。(因为超过直径点数的其他点需要在访问直径的途中去走分支再回来,所以要乘2)
如何求树的直径:
从树的任意一个结点出发,找最远的一个端点S,再从S出发找离S最远的一个端点T,则<S,T>之间的距离则为直径。
(可使用两次DFS/BFS)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <queue>
#include <map>
using namespace std;
const int maxn = 1e5+10;
const int mod = 2e9 + 7;
typedef long long ll;
typedef unsigned long long ull;
int n,m,u,v,len,q;
vector<int> G[maxn];
int dis[maxn];
void dfs(int u)
{
for(int i = 0; i < G[u].size(); i++){
if(!dis[G[u][i]]){
dis[G[u][i]] = dis[u] + 1;
dfs(G[u][i]);
}
}
}
int findst(int u)
{
memset(dis,0,sizeof(dis));
dis[u] = 1;
dfs(u);
int v = 1;
for(int i = 2; i <= n; i++){
if(dis[i] > dis[v])
v = i;
}
len = dis[v];
return v;
}
void work()
{
scanf("%d%d",&n,&m);
for(int i = 1; i <= n; i++)
G[i].clear();
for(int i = 0; i < n - 1; i++){
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
int s = findst(1);
findst(s);
for(int i = 0; i < m; i++){
scanf("%d",&q);
if(q <= len) printf("%d\n",q - 1);
else printf("%d\n",len - 1 + (q - len) * 2);
}
}
int main()
{
#ifdef LOCAL
freopen("case.in","r",stdin);
// freopen("case.out","w",stdout);
#endif
int t;
cin>>t;
while(t--)
work();
return 0;
}