ZOJ-3812 We Need Medicine(01背包+状压DP)

题意

现有 n 种药, m 种病,每种药有 W T 两种数据,每种病有 M , S 两种数据。现在需要尝试去治这些病,当且仅当所选药的 W 值之和等于药的 M 值,且所选药的 T 值之和等于药的 S 值时,是一种可行的方案,一种病只能用一次一种药。求其中一种可行解。
1 W , M 50
1 T , S 200000

思路

发现 W , M 的值很小, 2 50 又在 l o n g l o n g 的范围内,由此想到状压。用一个关于 S 的数组保存可行的 M 值的状态。然后用一个 S × M 的数组保存对应的药凑出这个数值时上一次选了哪种药,然后输出方案即可。

代码

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<map>
#define FOR(i,x,y) for(int i=(x);i<=(y);i++)
#define DOR(i,x,y) for(int i=(x);i>=(y);i--)
#define lowbit(x) (x&-(x))
typedef long long LL;
using namespace std;
LL dp[200003];
int a[53][200003];
int s[403],t[403],u[403],v[403];
map<LL,int>bin;

int main()
{
    FOR(i,0,53)bin[1LL<<i]=i;
    int T;
    scanf("%d",&T);
    while(T--)
    {
        memset(dp,0,sizeof(dp));
        memset(a,0,sizeof(a));
        int N,Q,n=0,m=0;
        dp[0]=1;
        scanf("%d%d",&N,&Q);
        FOR(i,1,N)scanf("%d%d",&s[i],&t[i]);
        FOR(i,1,Q)
        {
            scanf("%d%d",&u[i],&v[i]);
            n=max(n,u[i]);
            m=max(m,v[i]);
        }
        FOR(i,1,N)
            DOR(j,m,t[i])
            {
                LL tmp=dp[j];
                dp[j]|=(dp[j-t[i]])<<s[i]&((1LL<<51)-1);
                for(LL k=tmp^dp[j];k;k^=lowbit(k))
                    a[bin[lowbit(k)]][j]=i;
            }
        FOR(i,1,Q)
        {
            int U=u[i],V=v[i],choose=a[U][V];
            bool pres=0;
            if(!choose)
            {
                printf("No solution!\n");
                continue;
            }
            while(choose)
            {
                if(pres)printf(" ");
                printf("%d",choose);
                U-=s[choose];
                V-=t[choose];
                choose=a[U][V];
                pres=1;
            }
            printf("\n");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/paulliant/article/details/80828711
we