277人阅读 评论(0)

Park Visit

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3324    Accepted Submission(s): 1496

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

n个景点n-1条边，可见这个图是一个树，那么要走k个景点至少走多少路，就要尽可能少的走回头路，如果k个景点在一条直线，那是最好不过了走k-1的路程就够了，多以我们让他尽量走一个链状的路线，少走分叉的路线，那么我们从这受到启发，走树上最远距离，即树的直径，这些

原理: 设起点为u,第一次BFS找到的终点v一定是树的直径的一个端点
证明: 1) 如果u 是直径上的点，则v显然是直径的终点(因为如果v不是的话，则必定存在另一个点w使得u到w的距离更长，则于BFS找到了v矛盾)
2) 如果u不是直径上的点，则u到v必然于树的直径相交(反证),那么交点到v 必然就是直径的后半段了
所以v一定是直径的一个端点，所以从v进行BFS得到的一定是直径长度

ac代码：
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn=1e6+10;
struct Edge
{
int to,next,cap;
}edge[maxn*2];
void init()
{
tot=0;
}
{
edge[tot].to=v;
}
int vis[maxn],dis[maxn];
queue<int>que;
int tree(int s)
{
while(!que.empty())
{
que.pop();
}
int d,maxd=-9;
int u,v;
memset(vis,0,sizeof(vis));
vis[s]=1;
// for()
dis[s]=0;

que.push(s);
while(!que.empty())
{
u=que.front();
que.pop();
{
v=edge[i].to;
if(!vis[v])
{
vis[v]=1;
dis[v]=dis[u]+1;
if(dis[v]>maxd)
{
maxd=dis[v];
d=v;
}
que.push(v);
}
}
}

while(!que.empty())
que.pop();

memset(vis,0,sizeof(vis));
vis[d]=1;
dis[d]=0;
maxd=-9;
que.push(d);
while(!que.empty())
{
u=que.front();
que.pop();
{
v=edge[i].to;
if(!vis[v])
{
vis[v]=1;
dis[v]=dis[u]+1;
if(dis[v]>maxd)
maxd=dis[v];
que.push(v);
}
}
}
return maxd;

}
int main()
{
int t;
int n,m,k;
scanf("%d",&t);
while(t--)
{
int u,v;
init();
scanf("%d%d",&n,&m);
for(int i=1;i<n;i++)
{
scanf("%d%d",&u,&v);
}
int d=tree(1);
d++;
for(int i=0;i<m;i++)
{
scanf("%d",&k);
if(k<=d)
{
printf("%d\n",k-1);
}
else
{
printf("%d\n",(k-d)*2+d-1);
}
}
}

return 0;
}


个人资料
等级：
访问量： 7万+
积分： 3571
排名： 1万+
友情链接
博客专栏
 AC 文章：6篇 阅读：4325
最新评论