记录一个菜逼的成长。。
题目大意:
指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;
}
本文介绍了一种使用动态规划解决特定子集计数问题的方法,即计算在一定条件下子集的数量。通过定义状态和转移方程,给出了完整的C++实现代码。

被折叠的 条评论
为什么被折叠?



