hdu4697Park Visit(找节点)

来源:互联网 发布:社交媒体数据分析 编辑:程序博客网 时间:2024/06/05 12:41
Park Visit
Time Limit:3000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status

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? 

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

14 23 21 24 224

Sample Output

14
给出一个树,问要经过k个节点要走多少距离,每两个点之间距离为一;
先找出该树的最大直径;
直径+1>=k;
则距离为k-1;
否则为直径+(k-直径-1)×2;
#include<stdio.h>#include<string.h>#include<algorithm>#include<queue>using namespace std;#define M 310000struct 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);elseprintf("%d\n",ans+(k-ans-1)*2) ;       }      }} 


0 0
原创粉丝点击