HDU-4607(树形DP)

本文介绍了如何使用树形动态规划解决一个公园游览问题。给定一棵树状结构的公园,求解在只游览K个景点的情况下,最小的行走距离。解题思路包括考虑树的直径并在不同情况下计算最短路径。
摘要由CSDN通过智能技术生成

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

题目大意为:Claire和她的朋友想要游览一个有n个景点的公园,这n个景点形成一棵树,相邻两个景点之间的距离为1,我们最开始可以从任意一个景点出发,但是她们太累了,所以只想游览其中k个景点,现在我们要求Claire和她的朋友们游览k个景点需要走的最小距离。
解法:情况一:我们可以假设Claire可以不回头的走完这k个景点,也就是有一条路的长度大于等于k,那么此时Claire只需要直走就可以了,也就是答案为K-1,那么如果这条路最长,也就可以保证k小于等于这条路中的结点数量时,答案为k-1,而这条最长的路就是这颗树的直径,所以如果k小于等于树的直径所包含的点,就可以直接输出k-1啦;
情况二:然后我们考虑如果k小于这条路所包含的结点,我们假设Claire需要走一条路,这条路有x个结点,而k>x,那么我们就需要在这条路的中间去走分叉路,也就是走这条路上所包含的结点的子树中的结点,然后再回到这条路上,我们假设我们需要额外走y个结点,我们走过去的代价是y,走回来的代价和走过去的代价相同,所以我们总共需要走(2y)的距离,然后答案ans=x-1+2(k-x)=2*k-x-1。从这个式子中我们可以看出,如果想要答案最小,那么这条路径所包含的结点数x就要最大,也就是在情况一中所求的树的直径啦。
代码:

#include <stdio.h>
#include 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值