HDU 4607 Park Visit

38 篇文章 0 订阅
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?
 

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≤105), 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
 

Source
 

Recommend

liuyiding

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

SPFA~

两次遍历求直径,类似模板~


#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;

int t,n,m,x,y,k,fi[200010],cnt,dis[100005],tot,num,maxx;
bool b[100005];
queue<int> q;

struct node{
	int w,ne;
}a[200010];

void add(int u,int v)
{
	a[++cnt].w=v;a[cnt].ne=fi[u];fi[u]=cnt;
}

void spfa(int u)
{
	for(int i=1;i<=n;i++) dis[i]=0xffffff;
	q.push(u);dis[u]=0;b[u]=1;
	while(!q.empty())
	{
		int kkz=q.front();q.pop();b[kkz]=0;
		for(int i=fi[kkz];i!=-1;i=a[i].ne)
		  if(dis[a[i].w]>dis[kkz]+1)
		  {
		  	dis[a[i].w]=dis[kkz]+1;
		  	if(!b[a[i].w])
		  	{
		  		b[a[i].w]=1;q.push(a[i].w);
			}
		  }
	}
}

int main()
{
	scanf("%d",&t);
	while(t--)
	{
		memset(fi,-1,sizeof(fi));
		scanf("%d%d",&n,&m);
		for(int i=1;i<n;i++)
		{
			scanf("%d%d",&x,&y);
			add(x,y);add(y,x);
		}
		spfa(1);maxx=num=-1;
		for(int i=1;i<=n;i++)
		  if(dis[i]>maxx)
		  {
		  	maxx=dis[i];num=i;
		  }
		spfa(num);maxx=-1;
		for(int i=1;i<=n;i++) maxx=max(maxx,dis[i]);
		while(m--)
		{
			scanf("%d",&k);
			if(k<=maxx+1) printf("%d\n",k-1);
			else printf("%d\n",(k-maxx-1)*2+maxx);
		}
	}
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值