Park Visit
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2517 Accepted Submission(s): 1134
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?
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.
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
Source
Recommend
题意:有N个节点, N-1条边 , 每条边的长度为1, 问到达K个节点, 最少需要走多远的路。
思路: 求树的直径 (广搜两遍)
遍历一颗树首先不会超过 2 * N次。
因为在最长路里,每多走一个节点只需要走一条边, 而其他几点都需要经过两次。
所以在K <= 最长路包括的点 答案就是 k - 1 ;
在K > 最长路包括的点, 答案是 最长路 + (k - 最长路) * 2;
ac代码
#include<stdio.h>
#include<string.h>
#include<queue>
#include<iostream>
using namespace std;
int e,head[100010],dis[100010],vis[100010],cnt,s,maxn;
struct s
{
int u,v,next;
}edge[200020];
void add(int u,int v)
{
edge[cnt].u=u;
edge[cnt].v=v;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void bfs(int u)
{
int i;
queue<int>q;
memset(vis,0,sizeof(vis));
vis[u]=1;
dis[u]=0;
s=u;
maxn=-1;
q.push(u);
while(!q.empty())
{
int u=q.front();
q.pop();
for(i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(!vis[v])
{
vis[v]=1;
dis[v]=dis[u]+1;
q.push(v);
if(dis[v]>maxn)
{
maxn=dis[v];
s=v;
}
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,m,i;
scanf("%d%d",&n,&m);
memset(head,-1,sizeof(head));
cnt=0;
for(i=0;i<n-1;i++)
{
int a,b;
scanf("%d%d",&a,&b);
add(a,b);
add(b,a);
}
bfs(1);
bfs(s);
for(i=0;i<m;i++)
{
int k;
scanf("%d",&k);
if(k<=maxn+1)
{
printf("%d\n",k-1);
}
else
printf("%d\n",maxn+(k-maxn-1)*2);
}
}
}