Problem Description
Clare and her little friend, ykwd, are traveling 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 Clare 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! Clare 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.
Clare is too tired. Can you help her?
Resolution: similar to finding the longest root, that is
*__*__*__*__*__*__*__*__*__
|
****
|
**
The second is to traverse the longest tree root twice:
1. Start from any point A for the first time and find the point B that is farthest away.
2. Start from B and find the point C that is farthest from B. Then, the length of the BC line segment is the root length.
Proof: first, B must be the end of the diameter.
A) if A is one end of the diameter, B is obviously the other end of the diameter, and the conclusion is true.
B) if A is not the end of the diameter, the path (A-> B) must be at A point p with the diameter, and (p-> B) must be part of the diameter, B is the end of the diameter, and the conclusion is true.
1> Why must there be a point p?
If there is no intersection p, because the tree is connected, then add several sides to make the diameter go through (A-> B) A little p, the diameter will not become shorter.
2> Why (p-> B) must be a part of the diameter.
If not, (A-> B) is not the longest path from A to B.
Then everyone understands, set the root length of L, if you want to visit the scenic spots N <= L, then output N-1, otherwise, output L-1 + 2 * (N-L ).
The Code is as follows:
#include<string.h> #include<vector> #include<queue> using namespace std; int s[100005]; int main() { int N,m,n,a,b,i,l; scanf("%d",&N); while(N--) { scanf("%d%d",&m,&n); vector<int> Q[100005]; queue<int> q; memset(s,0,sizeof(s)); for(i=0;i<m-1;i++) { scanf("%d%d",&a,&b); Q[a].push_back(b); Q[b].push_back(a); } q.push(1);s[1]=1; while(!q.empty()) { a=q.front(); for(i=0;i<Q[a].size();i++) { if(!s[Q[a][i]]) q.push(Q[a][i]); } s[a]=1;q.pop(); } q.push(a);memset(s,0,sizeof(s));s[a]=1; while(!q.empty()) { a=q.front(); for(i=0;i<Q[a].size();i++) { if(!s[Q[a][i]]) {q.push(Q[a][i]);s[Q[a][i]]=s[a]+1;} } q.pop(); } l=s[a]; while(n--) { scanf("%d",&a); if(a<=l) printf("%d\n",a-1); else printf("%d\n",l-1+2*(a-l)); } } }