hdu4697Park Visit(找节点)

Park Visit
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? 

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

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) ;   
    }      

	}
	
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值