POJ_3181_Dollar_Dayz_(动态规划,完全部分和,完全背包)
2016-04-25 14:05
375 查看
描述
http://poj.org/problem?id=3181FJ有n元钱,有k种商品,各为1,2,...,k-1,k元,问有多少种花掉这n元钱的方法.
Dollar Dayz
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5858 | Accepted: 2197 |
Description
Farmer John goes to Dollar Days at The Cow Store and discovers an unlimited number of tools on sale. During his first visit, the tools are selling variously for $1, $2, and $3. Farmer John has exactly $5 to spend. He can buy 5 tools at $1 each or 1 tool at $3 and an additional 1 tool at $2. Of course, there are other combinations for a total of 5 different ways FJ can spend all his money on tools. Here they are:1 @ US$3 + 1 @ US$2Write a program than will compute the number of ways FJ can spend N dollars (1 <= N <= 1000) at The Cow Store for tools on sale with a cost of $1..$K (1 <= K <= 100).
1 @ US$3 + 2 @ US$1
1 @ US$2 + 3 @ US$1
2 @ US$2 + 1 @ US$1
5 @ US$1
Input
A single line with two space-separated integers: N and K.Output
A single line with a single integer that is the number of unique ways FJ can spend his money.Sample Input
5 3
Sample Output
5
Source
USACO 2006 January Silver
分析
这是一个完全部分和问题.对于多重部分和问题,可以用多重背包,但是由于有三层循环,会超时(即便使用二进制优化),所以有特殊的算法.而完全部分和问题可以直接用完全背包做.
注意:
1.是大数,要用高精度,或者两位分别存高低位:
unsigned long long 上限是1.8e19,所以每一位存1e17.
2.注意如果高位有数,低位要保证有前导0.
#include <cstdio> #include <algorithm> #define ull unsigned long long const int maxw=1005,maxn=105; const ull mod=100000000000000000; int W,N; ull dp[maxw][2]; void solve() { dp[0][0]=1; for(int i=1;i<=N;i++) { for(int j=i;j<=W;j++) { dp[j][0]+=dp[j-i][0]; dp[j][1]+=dp[j-i][1]; dp[j][1]+=dp[j][0]/mod; dp[j][0]%=mod; } } if(dp[W][1]) { printf("%llu",dp[W][1]); printf("%017llu\n",dp[W][0]); } else { printf("%llu\n",dp[W][0]); } } int main() { #ifndef ONLINE_JUDGE freopen("john.in","r",stdin); freopen("john.out","w",stdout); #endif scanf("%d%d",&W,&N); solve(); #ifndef ONLINE_JUDGE fclose(stdin); fclose(stdout); system("john.out"); #endif return 0; }View Code
相关文章推荐
- 在CentOS 7上利用systemctl添加自定义系统服务
- JS开发引用HTML DOM的location和document对象
- Linux下安装MySQL 5.7
- js和Android 的互相调用
- 统计学生成绩
- 偶然碰到的一段正则表达式解析
- JS开发引用HTML DOM的location和document对象
- 查看linux占用内存/CPU最多的进程
- [读书笔记]高阶函数
- 控制EasyUI DataGrid高度
- Centos 执行top命令详细解读
- [教程] 卡尔曼滤波简介及其算法实现代码(C++/C/MATLAB)
- Bool和bool
- Map
- 两个小数相加
- Linux性能监控工具dstat
- 对“视觉机器学习20讲配套仿真代码”的研究心得---贝叶斯学习
- Linux下git使用详解1
- 二、 sql*plus常用命令
- 使用hexo搭建属于自己的博客