您的位置:首页 > 其它

hdu4003 Find Metal Mineral 树形DP

2014-04-09 20:19 435 查看
[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
For each cases output one line with the minimal energy cost.

[align=left]Sample Input[/align]

3 1 1
1 2 1
1 3 1
3 1 2
1 2 1
1 3 1


[align=left]Sample Output[/align]
3
2


一棵树,有K个机器人,一个机器人从一个点到另外一个点要消耗能量,机器人开始都在S点,问走遍所有的点最少消耗多少能量。

树形DP的思想一般都是分组背包,每个子节点看成一个组,从每个组中再去dp每个状态。在这道题中状态就是在每个组中选k个机器人。

dp[u][i]代表节点u有i个机器人遍历所有子树的最小消耗,这道题很特别的想法是dp[u][0]代表节点u有1个机器人遍历完子树后又回到节点u的消耗,每次算dp[u][c]的时候先把dp[v][0]+2*w加上,这样可以保证子树的所有点都被走到。接着再去更新dp[u][c]的最小值。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cstdlib>
#define INF 0x3f3f3f3f
#define MAXN 10010
#define MAXM 15
#define MAXNODE 4*MAXN
#define pii pair<int,int>
using namespace std;
int N,S,K,vis[MAXN],dp[MAXN][MAXM];
vector<pii> V[MAXN];
void DFS(int u){
vis[u]=1;
int L=V[u].size();
for(int i=0;i<L;i++){
int v=V[u][i].first,w=V[u][i].second;
if(vis[v]) continue;
DFS(v);
for(int c=K;c>=0;c--){
dp[u][c]+=dp[v][0]+2*w;
for(int j=1;j<=c;j++) dp[u][c]=min(dp[u][c],dp[u][c-j]+dp[v][j]+j*w);
}
}
}
int main(){
freopen("in.txt","r",stdin);
while(scanf("%d%d%d",&N,&S,&K)!=EOF){
for(int i=1;i<=N;i++) V[i].clear();
for(int i=0;i<N-1;i++){
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
V[u].push_back(make_pair(v,w));
V[v].push_back(make_pair(u,w));
}
for(int i=0;i<=N;i++){
vis[i]=0;
for(int j=0;j<=K;j++) dp[i][j]=0;
}
DFS(S);
printf("%d\n",dp[S][K]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: