给机器人一棵树。有k个机器人从s点出发,求遍历所有点的最小花费。
典型的树形动态规划模型。
单独考虑每个机器人?
这样不合适,因为并不知道之前的机器人都干了什么事情。
遍历所有点的过程是全局的,强行拆开只会让设计变得麻烦。
考虑到这种全部覆盖的问题常常可以拆分为子问题,子问题也是完全覆盖的。
这意味着我们要把所有机器人放在一起考虑。
更直观地,f(x,c)表示以x为根的子树安排c个机器人做掉的mincost。
——真的合适吗?
就算是这样,我们还是不知道每个机器人到底做了什么,转移也就无从下手了。
考虑到每个机器人走的代价都是相同的,
如果不是回头的代价可能过大,一些路径显然不必要安排多个机器人来走。
这启示我们:“回头”可能是解题的关键。
把回头的代价放入状态?这当然不会合适;状态不是跟结点状态有关,就是跟机器人有关。
回头的代价是固定的。如果要考虑到回头,那就得跟机器人结合起来,
——有多少个机器人不回头,滞留在叶子结点上?
我们仍然需要保留“某个子树被完全遍历”的状态。
于是现在的状态就变成了,在有j个机器人滞留的情况下,遍历某子树的最小代价。
如果没有一个机器人滞留,又要完全遍历,那么就得有一个机器人进来绕一圈出去。
所以里面的每条边都会被走两次。
如果有机器人滞留,那么里面的某一个路径就会被少走。
——有两种思路。
一种是直接考虑遍历的最小代价,一种是考虑少走的最大代价。
并且,如果有机器人滞留,那么它一定会被分配到当前点的某个子节点里面。
于是考虑做背包。
遍历的最小代价
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cctype>
#include<cmath>
#include<ctime>
using namespace std;
#define add_edge(a, b, c) nxt[++tot]=head[a],head[a]=tot,to[tot]=b,val[tot]=c
int head[10005],nxt[20005],to[20005],val[20005];
int n, s, k, tot;
int f[10005][15];
void dfs(int x, int fa) {
for (int i = head[x]; i; i = nxt[i]) {
if (to[i] == fa) continue;
dfs(to[i], x);
for (int j = k; j >= 0; --j) {
f[x][j] += f[to[i]][0] + 2*val[i];
for (int p = 1; p <= j; ++p) {
f[x][j] = min(f[x][j], f[x][j-p]+f[to[i]][p]+p*val[i]);
}
}
}
}
int main() {
while (~scanf("%d%d%d", &n, &s, &k)) {
memset(f, 0, sizeof(f));
tot = 0;
memset(head, 0, sizeof(head));
for (int x, y, w, i = 1; i < n; ++i) {
scanf("%d%d%d", &x, &y, &w);
add_edge(x, y, w);
add_edge(y, x, w);
}
dfs(s, 0);
printf("%d\n", f[s][k]);
}
return 0;
}
最多能够少花多少代价
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cctype>
#include<cmath>
#include<ctime>
using namespace std;
#define add_edge(a, b, c) nxt[++tot]=head[a],head[a]=tot,to[tot]=b,val[tot]=c
int head[10005],nxt[20005],to[20005],val[20005];
int n, s, k, tot, sum;
int f[10005][15];
void dfs(int x, int fa) {
for (int i = head[x]; i; i = nxt[i]) {
if (to[i] == fa) continue;
dfs(to[i], x);
for (int j = k; j >= 1; --j) {
for (int p = 1; p <= j; ++p) {
f[x][j] = max(f[x][j], f[x][j-p]+f[to[i]][p]+(2-p)*val[i]);
}
}
}
}
int main() {
while (~scanf("%d%d%d", &n, &s, &k)) {
memset(f, 0, sizeof(f));
memset(head, 0, sizeof(head));
tot = sum = 0;
for (int x, y, w, i = 1; i < n; ++i) {
scanf("%d%d%d", &x, &y, &w);
add_edge(x, y, w);
add_edge(y, x, w);
sum += 2 * w;
}
dfs(s, 0);
printf("%d\n", sum - f[s][k]);
}
return 0;
}