题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5800
To My Girlfriend
Time Limit: 2000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1385 Accepted Submission(s): 537
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
∑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).
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
2016 Multi-University Training Contest 6
题意:给定n个数,选定其中若干数,这若干数的权值和为m,其中下标为i,j的必选,下标为k,l的必不选.问有多少种方案。
数据量还是很大的,方法不对很容易超时。
****p[i][j][s1][s2],代表的是前i个物品,总权值为j,已有s1个必选,s2必不选的方案数。那么对于当前一个状态,它有四种转移状态。
1.选中当前的,增加权值,增加必选个数。
2.选择当前的,增加权值,不增加必选个数。
3.不选中当前的,不增加权值,增加不必选个数。
4.不选中当前的,不增加权值,不增加不必选个数。**
因为i,j可以互换,l,k也可以互换,故而最后方案数乘以4即为所求。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int mod=1e9+7;
int dp[1005][1005][3][3];
int a[1005];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,s;
scanf("%d%d",&n,&s);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
memset(dp,0,sizeof(dp));
dp[1][a[1]][0][0]=1;
dp[1][a[1]][1][0]=1;
dp[1][0][0][0]=1;
dp[1][0][0][1]=1;
int tmp;
long long ans=0;
for(int i=2;i<=n;i++)
{
for(int j=0;j<=s;j++)
{
tmp=a[i]+j;
if(tmp<=s)
{//如果当前可以被选入,背包还能够再装
for(int k=0;k<=2;k++)
{//对于必选这一状态
dp[i][tmp][0][k]=(dp[i][tmp][0][k]+dp[i-1][j][0][k])%mod;//选择当前的,增加权值,不增加必选个数
dp[i][tmp][1][k]=(dp[i][tmp][1][k]+dp[i-1][j][0][k])%mod;//选中当前的,增加权值,增加必选个数
dp[i][tmp][1][k]=(dp[i][tmp][1][k]+dp[i-1][j][1][k])%mod;//选择当前的,增加权值,不增加必选个数
dp[i][tmp][2][k]=(dp[i][tmp][2][k]+dp[i-1][j][1][k])%mod;//选中当前的,增加权值,增加必选个数
dp[i][tmp][2][k]=(dp[i][tmp][2][k]+dp[i-1][j][2][k])%mod;//选择当前的,增加权值,不增加必选个数
}
}
for(int k=0;k<=2;k++)
{//对于必不选这一状态
dp[i][j][k][0]=(dp[i][j][k][0]+dp[i-1][j][k][0])%mod;//不选中当前的,不增加权值,不增加必选个数
dp[i][j][k][1]=(dp[i][j][k][1]+dp[i-1][j][k][0])%mod;//不选中当前的,不增加权值,增加不必选个数
dp[i][j][k][1]=(dp[i][j][k][1]+dp[i-1][j][k][1])%mod;//不选中当前的,不增加权值,不增加必选个数
dp[i][j][k][2]=(dp[i][j][k][2]+dp[i-1][j][k][1])%mod;//不选中当前的,不增加权值,增加不必选个数
dp[i][j][k][2]=(dp[i][j][k][2]+dp[i-1][j][k][2])%mod;//不选中当前的,不增加权值,不增加必选个数
}
}
}
for(int i=1;i<=s;i++)
ans=(ans+dp[n][i][2][2])%mod;
printf("%lld\n",ans*4%mod);
}
return 0;
}