Factories Gym - 102222G(2018宁夏邀请赛暨2019银川icpc网络预选赛)
第一場icpc網絡賽,出的去年寧夏邀請賽原題。c題還沒有讀完就有ak的了。。(滑稽)
Byteland has nn cities numbered from 11 to nn, and n?1n?1 bi-directional roads connecting them. For each pair of cities, the residents can arrive one from another one through these roads (which also means the road network in Byteland is a tree).
Ghaliyah, the queen of the land, has decided to construct kk new factories. To avoid contamination, she requires that a factory can locate at a city with only one road (which also means this city is a leaf in the road network). Besides, a city can only have one factory.
You, as the royal designer, are appointed to arrange the construction and meanwhile, minimize the sum of distances between every two factories.
Input
The input contains several test cases, and the first line is a positive integer TT indicating the number of test cases which is up to 103103.
For each test case, the first line contains two integers n (2≤n≤105)n (2≤n≤105) and k (1≤k≤100)k (1≤k≤100) indicating the number of cities in Byteland and the number of new factories which are asked to construct.
Each of the following n?1n?1 lines contains three integers u,v (1≤u,v≤n)u,v (1≤u,v≤n) and w (1≤w≤105)w (1≤w≤105) which describes a road between the city uu and the city vv of length ww.
We guarantee that the number of leaves in the road network is no smaller than kk, and the sum of nn in all test cases is up to 106106.
Output
For each test case, output a line containing Case #x: y, where x is the test case number starting from 11, and y is the minimum sum of distances between every two factories.
Example
Input
2
4 2
1 2 2
1 3 3
1 4 4
4 3
1 2 2
1 3 3
1 4 4
Output
Case #1: 5
Case #2: 18
題意,給一棵樹,給出k各點,這k個點只能在葉子節點上,問著k個點到達其余各點的距離和最小值是多少。
樹形dp。我們設定dp[x][i]代表著以x為祖先的子樹有i個葉子節點的到達其余各點的最小距離。狀態轉移方程為dp[x][i]=min(dp[x][i],dp[x][i-j]+dp[son][j]+(k-j)*j *w)。其中son代表著x的子節點。注意到,dp[x][i]的轉移與dp[x][i-j]相關,因此如果正著循環,可能會出現一個葉子節點多次更新一個父親的情況。為了避免這個問題,可用常用套路,即利用一個輔助數組存儲當前結果,到所有的轉移都判斷完畢后再重新復制給dp數組本身
代碼如下:
努力加油a啊,(o)/~
總結
以上是生活随笔為你收集整理的Factories Gym - 102222G(2018宁夏邀请赛暨2019银川icpc网络预选赛)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: No Pain No Game HDU
- 下一篇: Continuous Intervals