Description
Farmer John goes to Dollar days at the Cow Store and discovers a unlimited number of tools on sale. During his first visit, the tools is selling variously for $, $, and $. Farmer John has exactly $ to spend. He can buy 5 tools at $1 tool at $ and a additional 1 tool at $. Of course, there is other combinations for a total of 5 different ways FJ can spend all he money on tools. Here they is:
1 @ us$3 + 1 @ us$2 1 @ us$3 + 2 @ us$1 1 @ us$2 + 3 @ us$1 2 @ us$2 + 1 @ us$1 5 @ us$1
Write a program than would compute the number of ways FJ can spend N dollars (1 <= n <=) at the Cow Store for OLS on sale with a cost of $ $K (1 <= K <= 100).
Input
A single line with the space-separated integers:n and K.
Output
A single, with a single integer, is the number of the unique ways FJ can spend.
Sample Input
5 3
Sample Output
5
Source
Usaco 2006 January Silver
The subject is also a knapsack problem, that is, the need to ask how many combinations.
The novelty of the subject is:
1 use two long long to indicate the high and low of the large number can meet the non-overflow
2 high and low levels need careful calculation.
Modeling:
DP[I][J]: Indicates how many combinations of J coins are available when calculating the current I item.
Then state conversion: dp[i][j] = Dp[i-1][j] + Dp[i][j-i]//dp[i-1][j] represents the number of combinations calculated for the previous item, that is, the number of combinations that do not buy I items, Dp[i][j-i] Indicates the number of combinations of I items that are vacated I coins
Difficulties:
If you look closely, you will find that not only the two-dimensional arrays are not used, but even scrolling arrays are not needed.
As the following procedure, the direct use of a one-dimensional array can be answered.
#include <stdio.h> #include <vector> #include <string.h> #include <algorithm> #include < iostream> #include <string> #include <limits.h> #include <stack> #include <queue> #include <set> #include <map>using namespace std;const int max_n = 1001;long long hibit[max_n], Lowbit[max_n];const Lon G Long MOD = (long long) 1e18;//lowbit save 18 0, in order to output the same format, it will be rounded up, where long long can hold 19-digit void getcombinations (int N, int K) {Memse T (hibit, 0, sizeof (LONG) * (n+1)); memset (lowbit, 0, sizeof (long Long) * (n+1)); Lowbit[0] = 1ll;for (int i = 1; i < = K; i++) {for (int j = i; J <= N; j + +) {Lowbit[j] + = lowbit[j-i];//buy and do not buy I items is the current combination and Hibit[j] + + lowbit[j]/MOD + hibit[j-i] ;//Error: Forget Hibit[j-i]lowbit[j]%= mod;//Save low}}}int main () {int N, k;while (~scanf ("%d%d", &n, &k)) {getcombinations (N, K), if (Hibit[n] > 0LL) printf ("%lld", Hibit[n]);p rintf ("%lld\n", Lowbit[n]);} return 0;}
POJ 3181 Dollar Dayz Dynamic Programming method