【HDU5800】To My Girlfriend(DP + 滚动数组)

记录一个菜逼的成长。。

题目大意:
指n个物品里面子集的权值和为m,并且这个子集里面有i、j, 没有k、l的子集的个数;(i,j,k,l分别不同)
题解:
令dp[i][j][s1][s2]表示前i个物品填了j的体积,有s1个物品选为为必选,s2个物品选为必不选的方案数(0<=s1,s2<=2),则有转移方程dp[i][j][s1][s2] = dp[i - 1][j][s1][s2] + dp[i - 1][j - a[i]][s1 - 1][s2] + dp[i - 1][j][s1][s2 - 1],边界条件为dp[0][0][0][0] = 1,时间复杂度O(NS*3^2)。

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <list>
#include <deque>
#include <cctype>
#include <bitset>
#include <cmath>
using namespace std;
#define cl(a) memset(a,0,sizeof(a))
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<LL,LL> PLL;
const int INF = 0x3f3f3f3f;
const int N = 1000 + 10;
const int MOD = 1000000000 + 7;
int n,s;
int a[N];
LL dp[2][N][3][3];//第一维只有2  这是用了滚动数组
void add(LL &x,LL y)
{
    x += y;
    x = (x >= MOD ? x - MOD: x);
}
void solve()
{
    memset(dp,0,sizeof(dp));
    dp[0][0][0][0] = 1;
    int pos = 0;
    for( int i = 1; i <= n; i++ ){
        pos = !pos;
        for( int j = s; j >= 0; j-- ){
            for( int s1 = 0; s1 < 3; s1++ ){
                for( int s2 = 0; s2 < 3; s2++ ){
                    //不包含当前物品,也不选为必选或必不选;
                    dp[pos][j][s1][s2] = dp[!pos][j][s1][s2];
                    if(j >= a[i]){
                        //包含当前物品,不选为必选或必不选;
                        add(dp[pos][j][s1][s2],dp[!pos][j-a[i]][s1][s2]);
                        //包含当前物品,并选为必选;
                        if(s1 > 0)add(dp[pos][j][s1][s2],dp[!pos][j-a[i]][s1-1][s2]);
                    }
                    if(s2 > 0){
                        //不包含当前物品,并选为必不选;
                        add(dp[pos][j][s1][s2],dp[!pos][j][s1][s2-1]);
                    }
                }
            }
        }
    }
    LL ans = 0;
    for( int i = 1; i <= s; i++ ){
        add(ans,dp[pos][i][2][2]);
    }
    printf("%lld\n",(ans * 2) % MOD * 2 % MOD);//这里乘4 是因为i,j,k,l的位置可以互换算不同的方案
}
int main()
{
    int T;scanf("%d",&T);
    while(T--){
        scanf("%d%d",&n,&s);
        for( int i = 1; i <= n; i++ ){
            scanf("%d",a+i);
        }
        solve();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值