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.
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.
3 1 1 1 2 1 1 3 1 3 1 2 1 2 1 1 3 1
3
2
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,起点s,机器人数k,然后n-1行给出相互连接的两个点,还有这条路线的价值,问让机器人遍历所有边,最少花费值多少?
思路:
树形dp和背包,注意最重要的一点就是先把dp[u][0]放进背包,保证至少选一个,否则就是WA。。。这是最难想的一点
代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
const int maxn=10010;
struct Edge
{
int next;
int len;
int to;
}edge[maxn*3];
int head[maxn];
int dp[maxn][25];
int vis[maxn];
int n,k,s,tot;
void add(int u, int v,int len)
{
edge[++tot].next=head[u];
edge[tot].to=v;
edge[tot].len=len;
head[u]=tot;
}
void dfs(int now)
{
vis[now]=1;
for(int i=head[now];i!=0;i=edge[i].next){
int next=edge[i].to;
int len=edge[i].len;
if(vis[next])continue;
dfs(next);
for(int i=k;i>=0;i--)//背包
{
dp[now][i]+=dp[next][0]+2*len;//使得dp[u][0]至少选一个放进背包里
for(int j=0;j<=i;j++){
dp[now][i]=min(dp[now][i],dp[now][i-j]+dp[next][j]+j*len);
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
int u, v,len;
while(cin>>n>>s>>k)
{
tot=0;
memset(edge,0,sizeof(edge));
memset(dp,0,sizeof(dp));
memset(vis,0,sizeof(vis));
memset(head,0,sizeof(head));
for(int i=1;i<=n-1;i++)
{
cin>>u>>v>>len;
add(u,v,len);
add(v,u,len);
}
dfs(s);
cout<<dp[s][k]<<endl;
}
return 0;
}