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;
则距离为k-1;
否则为直径+(k-直径-1)×2;
#include<stdio.h> #include<string.h> #include<algorithm> #include<queue> using namespace std; #define M 310000 struct node { int v,next; }mp[M*3]; int cnt,head[M],dis[M],vis[M]; int ans,last; void add(int u,int v){ mp[cnt].v=v; mp[cnt].next=head[u]; head[u]=cnt++; } void bfs(int s){ queue<int> q; memset(vis,0,sizeof(vis)); memset(dis,0,sizeof(dis)); vis[s]=1; last=s; ans=0; q.push(s); while(!q.empty()){ int u=q.front(); q.pop(); for(int i=head[u];i!=-1;i=mp[i].next){ int v=mp[i].v; if(!vis[v] ){ vis[v]=1; dis[v]=dis[u]+1; if(ans<dis[v]){ ans=dis[v]; last=v; } q.push(v); } } } } int main(){ int t,n,m,a,b; scanf("%d",&t); while(t--){ scanf("%d%d",&n,&m); cnt=0; memset(head,-1,sizeof(head)); for(int i=0;i<n-1;i++){ scanf("%d %d",&a,&b); add(a,b); add(b,a); } bfs(1); bfs(last); int k; for(int i=0;i<m;i++) { scanf("%d",&k); if(k<=ans+1) printf("%d\n",k-1); else printf("%d\n",ans+(k-ans-1)*2) ; } } }