思路:令dp[i][j][s1][s2]为前i个物品选了j体积,选了s1个必选,s2个一定不选的方案数,然后就转移好了,其实就相当于一个普通的背包然后多加两维,很多想不懂怎么弄状态的其实都可以通过多加维数来确定,自己太菜比赛时候硬是推不出来....
#include<bits/stdc++.h>
using namespace std;
#define LL long long
const int maxn = 1005;
const int mod = 1e9+7;
int a[maxn];
int dp[maxn][maxn][3][3];
int n,s;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
memset(dp,0,sizeof(dp));
scanf("%d%d",&n,&s);
for(int i = 1;i<=n;i++)
scanf("%d",&a[i]);
dp[0][0][0][0]=1;
for(int i = 1;i<=n;i++)
{
for(int j = 0;j<=s;j++)
{
for(int s1 = 0;s1<=2;s1++)
{
for(int s2 = 0;s2<=2;s2++)
{
dp[i][j][s1][s2]=(dp[i][j][s1][s2]+dp[i-1][j][s1][s2])%mod;
if(j>=a[i])
dp[i][j][s1][s2]=(dp[i][j][s1][s2]+dp[i-1][j-a[i]][s1][s2])%mod;
if(s1>0&&j>=a[i])
dp[i][j][s1][s2]=(dp[i][j][s1][s2]+dp[i-1][j-a[i]][s1-1][s2])%mod;
if(s2>0)
dp[i][j][s1][s2]=(dp[i][j][s1][s2]+dp[i-1][j][s1][s2-1])%mod;
}
}
}
}
LL ans = 0;
for(int i = 1;i<=s;i++)
ans = (ans+dp[n][i][2][2])%mod;
printf("%lld\n",ans*4%mod);
}
}
Problem Description
Dear Guo
I never forget the moment I met with you.You carefully asked me: "I have a very difficult problem. Can you teach me?".I replied with a smile, "of course"."I have n items, their weight was a[i]",you said,"Let's define f(i,j,k,l,m) to be the number of the subset of the weight of n items was m in total and has No.i and No.j items without No.k and No.l items.""And then," I asked.You said:"I want to know
Sincerely yours,
Liao
I never forget the moment I met with you.You carefully asked me: "I have a very difficult problem. Can you teach me?".I replied with a smile, "of course"."I have n items, their weight was a[i]",you said,"Let's define f(i,j,k,l,m) to be the number of the subset of the weight of n items was m in total and has No.i and No.j items without No.k and No.l items.""And then," I asked.You said:"I want to know
∑i=1n∑j=1n∑k=1n∑l=1n∑m=1sf(i,j,k,l,m)(i,j,k,laredifferent)
Sincerely yours,
Liao
Input
The first line of input contains an integer T
(T≤15)
indicating the number of test cases.
Each case contains 2 integers n , s (4≤n≤1000,1≤s≤1000) . The next line contains n numbers: a1,a2,…,an (1≤ai≤1000) .
Each case contains 2 integers n , s (4≤n≤1000,1≤s≤1000) . The next line contains n numbers: a1,a2,…,an (1≤ai≤1000) .
Output
Each case print the only number — the number of her would modulo
109+7
(both Liao and Guo like the number).
Sample Input
2 4 4 1 2 3 4 4 4 1 2 3 4
Sample Output
8 8
Author
UESTC
Source