码迷,mamicode.com
首页 > 其他好文 > 详细

刷题总结——Bob's Race(hdu4123 树形dp+st表)

时间:2017-10-25 11:19:35      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:for   integer   cut   inter   hdu   first   seve   树形dp   最大   

题目:

Bob wants to hold a race to encourage people to do sports. He has got trouble in choosing the route. There are N houses and N - 1 roads in his village. Each road connects two houses, and all houses are connected together. To make the race more interesting, he requires that every participant must start from a different house and run AS FAR AS POSSIBLE without passing a road more than once. The distance difference between the one who runs the longest distance and the one who runs the shortest distance is called “race difference” by Bob. Bob does not want the “race difference”to be more than Q. The houses are numbered from 1 to N. Bob wants that the No. of all starting house must be consecutive. He is now asking you for help. He wants to know the maximum number of starting houses he can choose, by other words, the maximum number of people who can take part in his race.

Input

There are several test cases. The first line of each test case contains two integers N and M. N is the number of houses, M is the number of queries. 

The following N-1 lines, each contains three integers, x, y and z, indicating that there is a road of length z connecting house x and house y. 
The following M lines are the queries. Each line contains an integer Q, asking that at most how many people can take part in Bob’s race according to the above mentioned rules and under the condition that the“race difference”is no more than Q. 

The input ends with N = 0 and M = 0. 

(N<=50000 M<=500 1<=x,y<=N 0<=z<=5000 Q<=10000000) 

Output

For each test case, you should output the answer in a line for each query. 

Sample Input

5 5
1 2 3
2 3 4
4 5 3
3 4 2
1
2
3
4
5
0 0

Sample Output

1
3
3
3
5

题目大意:给定一颗树,编号为1--n,每个顶点可以作为起点走最长的一段距离(未知)对于每个询问q,找到最长的一段连续编号的顶点使得编号中的最长距离的最大值与最小值的差小于q

题解:

  首先要计算最长距离···我们可以用前面的book of evil的dp思想,这里就不多说了··

  然后对于每个询问··我们可以采用类似于单调队列的思想···用同过两个指针的移动来计算答案(具体看代码),然后对于两个指针间的区间我们需要一个快速的算法计算出最大最小值···可以使用st表来解决

刷题总结——Bob's Race(hdu4123 树形dp+st表)

标签:for   integer   cut   inter   hdu   first   seve   树形dp   最大   

原文地址:http://www.cnblogs.com/AseanA/p/7727248.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!