标签:
Park Visit
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2506 Accepted Submission(s): 1128
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
Sample Output
题意:给定一棵树,从树中的任意选一个顶点出发,遍历K个点的最短距
离是多少?(每条边的长度为1)
解析:求出树的最长链,若最长链的长度为len,如果K<=len+1,那么
答案就是K-1,否则就是(K-len-1)*2+len(这个可以自己面图想想)。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int maxn=100010;
int n,m,a[maxn];
vector <int> G[maxn];
void initial()
{
for(int i=0;i<maxn;i++) G[i].clear();
memset(a,0,sizeof(a));
}
void input()
{
int u,v;
scanf("%d %d",&n,&m);
for(int i=1;i<n;i++)
{
scanf("%d %d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
}
void dfs(int u,int v,int depth)
{
a[v]=depth;
for(int i=0;i<G[v].size();i++)
{
int vv=G[v][i];
if(vv==u) continue;
dfs(v,vv,depth+1);
}
}
void solve()
{
int Max=-1,c=0,t;
dfs(-1,1,0);
for(int i=1;i<=n;i++) if(Max<a[i]) Max=a[i],c=i;
Max=-1;
memset(a,0,sizeof(a));
dfs(-1,c,0);
for(int i=1;i<=n;i++) Max=max(Max,a[i]);
for(int i=0;i<m;i++)
{
scanf("%d",&t);
if(t<=Max+1) printf("%d\n",t-1);
else printf("%d\n",2*(t-Max-1)+Max);
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
initial();
input();
solve();
}
return 0;
}
hdu 4607 Park Visit(树的直径)
标签:
原文地址:http://blog.csdn.net/u012596172/article/details/43054519