Find Metal Mineral
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65768/65768 K (Java/Others)Total Submission(s): 2423 Accepted Submission(s): 1103
Problem Description
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.
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 1
Sample Output
3 2HintIn the first case: 1->2->1->3 the cost is 3; In the second case: 1->2; 1->3 the cost is 2;
弱渣,分组背包都不会,现学的分组背包,对于每一个节点,它可以向它的一个儿子派一个机器人再回来,我们记为dp[son][0],还可以派一个,记为dp[son][1],派两个记为dp[son][2].....派k个记为dp[son][k],这样就转化为分组背包了。
代码:
//265ms
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=10000+1000;
int dp[maxn][20];
int head[maxn];
int t,k;
struct node
{
int v;
int next;
int cost;
}edge[maxn*3];
void add(int v,int u,int cost)
{
edge[t].v=v;
edge[t].next=head[u];
edge[t].cost=cost;
head[u]=t++;
edge[t].v=u;
edge[t].next=head[v];
edge[t].cost=cost;
head[v]=t++;
}
void dfs(int u,int father)
{
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(v==father)
continue;
dfs(v,u);
for(int l=k;l>=0;l--)
{
dp[u][l]+=(dp[v][0]+2*edge[i].cost);
for(int j=1;j<=l;j++)
{
dp[u][l]=min(dp[u][l],dp[u][l-j]+dp[v][j]+j*edge[i].cost);
}
}
}
}
int main()
{
int n,s;
while(~scanf("%d%d%d",&n,&s,&k))
{
t=0;
memset(head,-1,sizeof(head));
memset(dp,0,sizeof(dp));
int u,v,cost;
for(int i=1;i<n;i++ )
{
scanf("%d%d%d",&u,&v,&cost);
add(u,v,cost);
}
dfs(s,-1);
printf("%d\n",dp[s][k]);
}
return 0;
}