Humans have discovered a kind of new metal mineral on Mars which are distributed in point‐like with paths connecting each of them which formed a tree. Now Humans launches k robots on Mars to collect them, and due to the unknown reasons, the landing site S of all robots is identified in advanced, in other word, all robot should start their job at point S. Each robot can return to Earth anywhere, and of course they cannot go back to Mars. We have research the information of all paths on Mars, including its two endpoints x, y and energy cost w. To reduce the total energy cost, we should make a optimal plan which cost minimal energy cost.
Input
There are multiple cases in the input.
In each case:
The first line specifies three integers N, S, K specifying the numbers of metal mineral, landing site and the number of robots.
The next n‐1 lines will give three integers x, y, w in each line specifying there is a path connected point x and y which should cost w.
1<=N<=10000, 1<=S<=N, 1<=k<=10, 1<=x, y<=N, 1<=w<=10000.Output
For each cases output one line with the minimal energy cost.
Sample Input
3 1 1 1 2 1 1 3 1 3 1 2 1 2 1 1 3 1Sample Output
3 2Hint
In the first case: 1->2->1->3 the cost is 3; In the second case: 1->2; 1->3 the cost is 2;
题目大意:
给一棵n个节点的树, 节点编号为1~n, 每条边都有一个花费值.
有k个机器人从S点出发, 问让机器人遍历所有边,最少花费值多少?
分析:
很明显的树上dp,dp[i][x]表示该子树根上来了i个机器人的最小花费。
状态转移部分:
for(int k=K;k>=0;k--){
dp[k][x]+=dp[0][v]+2*len;
for(int j=1;j<=k;j++)
dp[k][x]=min(dp[k][x],dp[k-j][x]+dp[j][v]+len*j);
}
在每个节点,要么不走下去,dp[k][x]+=dp[0][v]+2*len(这里走下去是指机器人下去之后不回到根)dp[0][v]即先让一个机器人从v走下去遍历所有的边,再回到v,回来后再走前几个儿子即dp[k][x],因而直接加上去就行了。要么走下去,dp[k][x]=min(dp[k][x],dp[k-j][x]+dp[j][v]+len*j);
AC代码:
#include<bits/stdc++.h>
#define MXN 10005
using namespace std;
int n,s,K;
int dp[15][MXN];
int hd[MXN],nt[MXN<<1],to[MXN<<1],V[MXN<<1],ct;
void Add(int x,int y,int v){
nt[++ct]=hd[x];
to[ct]=y;
V[ct]=v;
hd[x]=ct;
}
void DP(int x,int fa){
for(int i=hd[x];i;i=nt[i]){
int v=to[i],len=V[i];
if(v==fa)continue;
DP(v,x);
for(int k=K;k>=0;k--){//倒序
dp[k][x]+=dp[0][v]+2*len;
for(int j=1;j<=k;j++)
dp[k][x]=min(dp[k][x],dp[k-j][x]+dp[j][v]+len*j);
}
}
}
int main(){
while(~scanf("%d%d%d",&n,&s,&K)){
ct=0;
memset(hd,0,sizeof(hd));
memset(dp,0,sizeof(dp));
for(int i=1;i<n;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
Add(a,b,c);
Add(b,a,c);
}
DP(s,-1);
printf("%d\n",dp[K][s]);
}
return 0;
}