bzoj 1042: [HAOI2008]硬币购物(容斥原理)
2016-05-05 19:11
323 查看
1042: [HAOI2008]硬币购物
Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 1803 Solved: 1051
[Submit][Status][Discuss]
Description
硬币购物一共有4种硬币。面值分别为c1,c2,c3,c4。某人去商店买东西,去了tot次。每次带di枚ci硬币,买si的价值的东西。请问每次有多少种付款方法。
Input
第一行 c1,c2,c3,c4,tot 下面tot行 d1,d2,d3,d4,s,其中di,s<=100000,tot<=1000Output
每次的方法数Sample Input
1 2 5 10 23 2 3 1 10
1000 2 2 2 900
Sample Output
427
HINT
Source
[Submit][Status][Discuss]
题解:
转载自http://hzwer.com/5286.html
设F[i]为不考虑每种硬币的数量限制的情况下,得到面值i的方案数。则状态转移方程为
F[i]=Sum{F[i-C[k]] | i-C[k]>=0 且 k=1..4}
为避免方案重复,要以k为阶段递推,边界条件为F[0]=1,这样预处理的时间复杂度就是O(S)。
接下来对于每次询问,奇妙的解法如下:根据容斥原理,答案为 得到面值S的超过限制的方案数 – 第1种硬币超过限制的方案数 – 第2种硬币超过限制的方案数 – 第3种硬币超过限制的方案数 – 第4种硬币超过限制的方案数 + 第1,2种硬币同时超过限制的方案数 + 第1,3种硬币同时超过限制的方案数 + …… + 第1,2,3,4种硬币全部同时超过限制的方案数。
当第1种硬币超过限制时,只要要用到D[1]+1枚硬币,剩余的硬币可以任意分配,所以方案数为 F[ S – (D[1]+1)C[1] ],当且仅当(S – (D[1]+1)C[1])>=0,否则方案数为0。其余情况类似,每次询问只用问16次,所以询问的时间复杂度为O(1)。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #define N 100003 #define LL long long using namespace std; int n,m; LL c[10],d[10],f ,s,ans; void dfs(int x,int y,LL sum) { if (sum<0) return; if (x==5) { if (y&1) ans-=f[sum]; else ans+=f[sum]; return; } dfs(x+1,y,sum); dfs(x+1,y+1,sum-(d[x]+1)*c[x]); } int main() { for (int i=1;i<=4;i++) scanf("%lld",&c[i]); f[0]=1; for (int j=1;j<=4;j++) for (int i=c[j];i<=100000;i++) f[i]+=f[i-c[j]]; scanf("%d",&m); for (int l=1;l<=m;l++) { for (int i=1;i<=4;i++) scanf("%lld",&d[i]); scanf("%lld",&s); ans=0; dfs(1,0,s); printf("%lld\n",ans); } }
相关文章推荐
- OpenCV检测图像SURF特征
- Linux下快速安装和配置jdk8
- Leetcode - Reverse Vowels of a String
- 设计模式6大设计原则
- APUE笔记:alarm和pause竞争
- Android利用Gson库解析复杂结构的JSON数据
- iOS应用架构谈 view层的组织和调用方案
- BootStrap应用实例学习笔记
- UILabel 标签
- WIN10使用VS2008通过网络在WINCE6.0模拟器调试应用
- linux下利用valgrind工具进行内存泄露检测和性能分析
- Error running app: Instant Run requires 'Tools | Android | Enable ADB integration' to be enabled.
- 修改IntelliJ IDEA中Maven项目的默认JDK版本
- 初学android开发--Fragment
- Java语法:与c++不同的地方
- 写了2个简单的工具脚本用来分发hdfs集群上的文件到所有节点,和远程执行命令
- php第十一节课
- Objective-C:KVC
- UILabel 实现计算器界面
- 274. H-Index