当前位置: 代码迷 >> 综合 >> Starship Troopers 树上分组背包
  详细解决方案

Starship Troopers 树上分组背包

热度:52   发布时间:2024-01-04 10:26:18.0

传送门

Problem Description

You, the leader of Starship Troopers, are sent to destroy a base of the bugs. The base is built underground. It is actually a huge cavern, which consists of many rooms connected with tunnels. Each room is occupied by some bugs, and their brains hide in some of the rooms. Scientists have just developed a new weapon and want to experiment it on some brains. Your task is to destroy the whole base, and capture as many brains as possible.

To kill all the bugs is always easier than to capture their brains. A map is drawn for you, with all the rooms marked by the amount of bugs inside, and the possibility of containing a brain. The cavern’s structure is like a tree in such a way that there is one unique path leading to each room from the entrance. To finish the battle as soon as possible, you do not want to wait for the troopers to clear a room before advancing to the next one, instead you have to leave some troopers at each room passed to fight all the bugs inside. The troopers never re-enter a room where they have visited before.

A starship trooper can fight against 20 bugs. Since you do not have enough troopers, you can only take some of the rooms and let the nerve gas do the rest of the job. At the mean time, you should maximize the possibility of capturing a brain. To simplify the problem, just maximize the sum of all the possibilities of containing brains for the taken rooms. Making such a plan is a difficult job. You need the help of a computer.

解析与坑点

  1. 特判m = 0 直接输出 0,里面会有房间bugs = 0,但brain != 0的数据,这个时候m = 0就会可以获得脑子,但是好像题目不允许房价没有士兵,也许没有士兵就没人去拿脑子了吧hhhh
  2. 如果要到这个房间的下一个房间,那么这个房间,一定要派足够的士兵消灭所有bugs并且获得脑子。每个房子又可以选择给它分配不同数量的士兵到不同的子房间里,那么就是一个分组背包了,每个物品组至少要留下空间选择父房间。
  3. 每个节点做一个 m*m的分组背包,一共n个结点,时间复杂度n * m * m = 10^6 dfs可做


代码

#include <bits/stdc++.h>
using namespace std;const int N = 105;
int h[N], to[N << 1], ne[N << 1], v[N], w[N], dp[N][N];
int cnt = 0;
void add(int x, int y)
{
    to[++cnt] = y;ne[cnt] = h[x];h[x] = cnt;
}
int n, m;void dfs(int u, int fa)
{
    int c = (v[u] + 19) / 20;for (int i = c; i <= m; ++i) // n * mdp[u][i] = w[u];for (int i = h[u]; ~i; i = ne[i]){
    int x = to[i];if (x == fa)continue;dfs(x, u);//cout << " fds " << endl;int cx = (v[x] + 19) / 20;for (int j = m; j >= c; --j){
     // n * m * mfor (int k = 1; k <= j - c; ++k)dp[u][j] = max(dp[u][j], dp[u][j - k] + dp[x][k]);}}
}int main()
{
    while (scanf("%d %d", &n, &m) && n != -1 && m != -1){
    memset(h, -1, sizeof h);memset(dp, -0x3f, sizeof dp);cnt = 0;for (int i = 1; i <= n; ++i){
    scanf("%d %d", &v[i], &w[i]);}for (int i = 1; i < n; ++i){
    int x, y;scanf("%d %d", &x, &y);add(x, y);add(y, x);}if (m == 0){
    printf("0\n");continue;}dfs(1, -1);printf("%d\n", max(0, dp[1][m]));}return 0;
}/*5 10 50 10 40 10 40 20 65 30 70 30 1 2 1 3 2 4 2 5 1 1 20 7 -1 -1 */