您的位置:首页 > 其它

hdu 4607 Park Visit(树直径)

2014-10-18 00:27 399 查看
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


题意:给定一棵树,从树中的任意选一个顶点出发,遍历K个点的最短距离是多少?(每条边的长度为1)

解析:就是求树的最长链,假设求出的树的最长链所包含的点数为m,那么如果K<=m,那么答案就是K-1,否则就是(K-m)*2+m-1. (K-m)*2为重复路径。

#include <iostream>
#include <string.h>
#include <stdio.h>
const int MAX=300005;
using namespace std;
struct node
{
int u,v;
int next;
}e[MAX];
int head[MAX];
bool vis[MAX];
int n,Max;
int k;
void dfs(int u,int len,bool vis[])
{
if(len>Max)
{
Max=len;
k=u;
}
for (int i=head[u]; i!=-1; i=e[i].next)
{
if(!vis[e[i].v])
{
vis[e[i].v]=true;
dfs(e[i].v, len+1, vis);
vis[e[i].v]=false;
}
}
}
int main()
{
int T;
int m;
scanf("%d",&T);
while (T--)
{
scanf("%d%d",&n,&m);

int a,b;
int j=1;
for (int i=1; i<=n; i++)
{
vis[i]=false;
head[i]=-1;
}
for (int i=1; i<n; i++)
{
scanf("%d%d",&a,&b);
e[j].u=a;
e[j].v=b;
e[j].next=head[a];
head[a]=j++;

e[j].u=b;
e[j].v=a;
e[j].next=head[b];
head[b]=j++;
}
Max=-1;
vis[1]=true;
dfs(1, 0, vis);
for (int i=1; i<=n; i++)
{
vis[i]=false;
}
vis[k]=true;
dfs(k, 0, vis);
for (int i=0; i<m; i++)
{
scanf("%d",&k);
if(k<=Max+1)
{
printf("%d\n",k-1);
}
else
{
printf("%d\n",Max+(k-Max-1)*2);
}
}

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: