您的位置:首页 > 其它

Hdu 4607 Park Visit【思维+求树的最长链】好题!好题~

2017-06-20 21:47 399 查看


Park Visit

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 3696    Accepted Submission(s): 1654


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

 

Source

2013 Multi-University Training Contest 1

题目大意:

给你N个点组成的一棵树,现在有M个查询,每个查询表示我们想以任意一个点作为起点,游玩k个景点的最少路径花费。

思路:

1、我们贪心的去想,肯定我们希望走的路径是形成一条链的,这样的路径长度为K-1.

所以这里我们要找一下树的最长链。

树的最长链要怎样找呢?其实也很简单,以任意一个点(我们不妨设定为1)作为根去深搜,搜以1为根的最深的深度的叶子节点,设定它为Root.我们再以这个Root作为根去搜他的树高即可。

假设有:

1-2

2-3

1-4

4-5

5-6

我们第一次从1搜到最深的子树的叶子节点6.我们再以6为Root搜树高为6.那么这棵树的最长链长度就是6.

2、如果我们要遍历的点的个数大于这个最长链怎么办呢?

我们贪心的去走的话,还是要以这条最长链为主路径,当有岔路的时候,进去遍历一下再出来回归主路径继续走下去,当我们岔路遍历的景点的个数足够多了的时候,我们就不要继续走岔路了,显然我们走到岔路中再出来,走进去的每一条边都遍历了两次,那么对应这种情况的结果其实就是:2*(k-最长链长度)+最长链长度-1.

Ac代码:

#include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
int root;
int maxn;
vector<int >mp[150000];
void Dfs(int u,int from,int cont)
{
if(cont>maxn)
{
maxn=cont;
root=u;
}
for(int i=0;i<mp[u].size();i++)
{
int v=mp[u][i];
if(v==from)continue;
else
{
Dfs(v,u,cont+1);
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,m;
scanf("%d%d",&n,&m);
root=1;
maxn=0;
for(int i=1;i<=n;i++)mp[i].clear();
for(int i=0;i<n-1;i++)
{
int x,y;
scanf("%d%d",&x,&y);
mp[x].push_back(y);
mp[y].push_back(x);
}
Dfs(1,-1,1);
Dfs(root,-1,1);
while(m--)
{
int q;
scanf("%d",&q);
if(q<=maxn)
{
printf("%d\n",q-1);
}
else printf("%d\n",maxn-1+2*(q-maxn));
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Hdu 4607