111人阅读 评论(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

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

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：61797次
• 积分：3355
• 等级：
• 排名：第10445名
• 原创：277篇
• 转载：17篇
• 译文：0篇
• 评论：9条
博客专栏
 AC 文章：6篇 阅读：3859
最新评论