poj1155 分类: poj 2015-07-20 10:24 11人阅读 评论(0) 收藏


树形背包


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <string>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <utility>
#include <iostream>
#include <algorithm>

const int maxn = 3005, INF = 0x3f3f3f3f;

int n, m, fa[maxn], cost[maxn];
int dp[maxn][maxn], size[maxn];

int main()
{
#ifndef ONLINE_JUDGE
    freopen("poj1155.in","r",stdin);
    freopen("poj1155.out","w",stdout);
#endif

    std::cin >> n >> m;

    for(int i = 1, k, A, C; i <= n - m; i++)
    {
        std::cin >> k;
        for(int j = 1; j <= k; j++)
        {
            std::cin >> A >> C;
            fa[A] = i, cost[A] = C;
        }
    }
    for(int i = n - m + 1, Pay; i <= n; i++)
    {
        std::cin >> Pay;
        cost[i] -= Pay;
    }

    memset(dp, INF, sizeof(dp));
    memset(dp[0], 0, sizeof(dp[0]));

    for(int i = n; i > 1; i--)
    {
        if(i > n - m) size[i] = 1, dp[1][i] = 0;

        size[fa[i]] += size[i];

        for(int k = size[fa[i]]; k > 0; k--)
            for(int j = std::min(size[i], k); j > 0; j--)
            {
                int tmp = dp[k-j][fa[i]] + dp[j][i] + cost[i];
                dp[k][fa[i]] = std::min(dp[k][fa[i]], tmp);
            }
    }

    for(int i = m; i >= 0 ; i--)
        if(dp[i][1] <= 0)
        {
            std::cout << i;
            break;
        }

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-07-20 10:24  <Dash>  阅读(117)  评论(0编辑  收藏  举报