码迷,mamicode.com
首页 > 其他好文 > 详细

zoj 3812 We Need Medicine(01背包)

时间:2014-09-10 17:46:10      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   os   io   ar   for   sp   on   

题目链接:zoj 3812 We Need Medicine

题目大意:有n中化学成分,每种成分要么选取重量Wi,获得Ti的TEV值,要么不取,获得0的TEV值。现在对于每种病

毒,要求配置质量为Mi的药物,并且TEV值为Si,求化学成分组成。

解题思路:看了别人的题解,以前居然不知道背包转移可以用二进制。

因为质量总共才50,所以用一个long long的二进制数表示说哪些质量是可祖长的,这样的话只要开一个20W的数组

s,s[i]表示说TEV值为i时质量可以为多少。然后每次在用lowbit处理出新增的可能,用dp[i][j]记录路径。

#include <cstdio>
#include <cstring>
#include <map>
#include <algorithm>

using namespace std;

#define lowbit(x) ((x)&(-x))

typedef unsigned long long ull;
typedef long long ll;
const int maxn = 405;
const int maxt = 200000;

int N, Q, W[maxn], T[maxn];
short dp[maxt + 5][52];
map<ll, int> G;
ull s[maxt];

void init () {
    scanf("%d%d", &N, &Q);
    for (int i = 1; i <= N; i++)
        scanf("%d%d", &W[i], &T[i]);

    ull bit = (1LL<<51) - 1;
    memset(s, 0, sizeof(s));
    memset(dp, 0, sizeof(dp));
    s[0] = 1;

    for (int i = 1; i <= N; i++) {
        for (int j = maxt; j >= T[i]; j--) {
            ull v = s[j];

            s[j] |= ((s[j-T[i]]<<W[i]) & bit);

            for (ll k = s[j]^v; k != 0; k -= lowbit(k))
                dp[j][G[lowbit(k)]] = i;
        }
    }
}

int main () {

    for (int i = 0; i <= 50; i++)
        G[1LL<<i] = i;

    int cas;
    scanf("%d", &cas);
    while (cas--) {
        init();

        int x, y;
        while (Q--) {
            scanf("%d%d", &x, &y);

            if (dp[y][x]) {
                int u = dp[y][x];
                printf("%d", u);
                while (u) {
                    y -= T[u];
                    x -= W[u];
                    u = dp[y][x];

                    if (u)
                        printf(" %d", u);
                }
                printf("\n");
            } else
                printf("No solution!\n");
        }
    }
    return 0;
}

zoj 3812 We Need Medicine(01背包)

标签:style   http   color   os   io   ar   for   sp   on   

原文地址:http://blog.csdn.net/keshuai19940722/article/details/39183721

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!