HDU 5291 Candy Distribution DP 差分 前缀和优化
2016-03-14 22:11
471 查看
Candy Distribution
题目连接:
http://acm.hdu.edu.cn/showproblem.php?pid=5291Description
WY has n kind of candy, number 1-N, The i-th kind of candy has ai. WY would like to give some of the candy to his teammate Ecry and lasten. To be fair, he hopes that Ecry’s candies are as many as lasten's in the end. How many kinds of methods are there?Input
The first line contains an integer T<=11 which is the number of test cases.Then T cases follow. Each case contains two lines. The first line contains one integer n(1<=n<=200). The second line contains n integers ai(1<=ai<=200)
Output
For each test case, output a single integer (the number of ways that WY can distribute candies to his teammates, modulo 109+7 ) in a single line.Sample Input
21
2
2
1 2
Sample Output
24
Hint
题意
有n种糖果,每种糖果ai个,然后你要把糖果分给A,B两个人,问你使得两个人糖果个数都相同的方案有多少种。题解:
最简单的dp:dp[i][j]表示考虑到第i种糖果,现在A比B多j个,那么dp[i][x-y+j]+=dp[i-1][j],如果x+y<=ai的话
当然这种dp肯定会tle的。
然后优化一下,发现dp[i][j]=dp[i][j-k]*((a[i]-k)/2+1),表示你先扔了K个给A,然后剩下的水果AB平分。
这个东西我们发现,是一个分奇数和偶数的等差数列的东西。
1 1 2 2 3 3 4 4 ..... n n n n-1 n-1 ..... 3 3 2 2 1 1 系数是这样的。
显然可以分奇偶前缀和+差分+递推就可以O(1)得到每一个dp[i][j]了。
然后这道题就可以搞了。
代码
#include<bits/stdc++.h> using namespace std; const int maxn = 8e4+5; const int mod = 1e9+7; int dp[maxn],sum[2][maxn],a[205],tot; void solve() { memset(dp,0,sizeof(dp)); memset(sum,0,sizeof(sum)); tot=0; int n;scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]),tot+=a[i]; if(tot%2==1)tot++; int M=tot*2; dp[tot]=1; for(int i=1;i<=n;i++) { sum[0][0]=dp[0]; sum[1][0]=0; for(int j=1;j<=M;j++) { sum[0][j]=sum[0][j-1]; sum[1][j]=sum[1][j-1]; if(j%2==1)sum[1][j]+=dp[j]; else sum[0][j]+=dp[j]; sum[0][j]%=mod; sum[1][j]%=mod; } long long res = 0; for(int j=0;j<=a[i];j++) res = (res + 1ll*dp[j]*((a[i]-j)/2+1))%mod; int o = (a[i]%2)^1; for(int j=0;j<=M;j++) { dp[j]=res; res+=sum[o][(j+a[i]+1)]; res%=mod; res-=sum[o][j]; res%=mod; o^=1; res-=sum[o][j]; res%=mod; res+=sum[o][max((j-a[i]-1),0)]; res%=mod; } } dp[tot]=dp[tot]%mod; dp[tot]=(dp[tot]+mod)%mod; cout<<dp[tot]<<endl; } int main() { int t;scanf("%d",&t); while(t--)solve(); return 0; }
相关文章推荐
- Longest Substring Without Repeating Characters
- MySQL的高级查询
- Longest Substring Without Repeating Characters
- 解决使用tomcat6-maven-plugin时的"can not invoke tomcat manager"问题
- maven+eclipse基础
- C++ 多线程并发控制——互斥锁 pthread_mutex
- 二分查找算法----递归&&非递归
- 软件工程作业 四则运算(二)
- 第一堂第一次
- 使用axis调用webservice
- matlab和C++混编(1)配置开发环境
- Problem F: 结构体--学生信息排序
- 安卓开发常见问题
- 巧妙利用单调队列(12哈工程多校)(3530)
- Fiddler
- 20135323符运锦----第四周:扒开系统调用的“三层皮”
- 转:Automatic Layout Groups
- 启动画面的细节处理
- 开发中遇到的坑
- java中synchronized锁定对象问题