USACO Money System 背包9讲,动态规划,母函数

来源:互联网 发布:木塑板的危害 知乎 编辑:程序博客网 时间:2024/05/10 15:27

一、使用动态规划 (注意阅读dd大神的背包问题九讲)

设dp[i,j]表示前i种货币构成j的方法数,用cc记录货币的面值,状态转移方程为:

dp[i,j]=dp[i-1,j];    不用第i种货币

dp[i,j]=dp[i-1,j]+dp[i,j-cc[i]]    用第i种货币,j>=cc[i]


二、构造母函数

也许麻烦了点,但也是一种方法。

原问等价于求一个形如a1X1+a2X2+...+avXv=n的方程的非负整数解的个数。构造生成函数f(x)=(x^0+x^a1+x^(2*a1)+x^(3*a1)+...)(x^0+x^a2+x^(2*a2)+x^(3*a2)+...)...(x^0+x^av+x^(2*av)+x^(3*av)+...) 则x^n的系数就是所求。


我的代码:第一遍到 test11 的时候老出错,后来发现结果太大(18390132498),int,long的范围都不够,只好用了long long类型(长度是8Byte)

/* ID: wangxin12 PROG: money LANG: C++ */ #include <iostream>#include <vector>#include <fstream>#include <string>using namespace std;int V, N;  //V <= 25, N <= 10000ifstream fin("money.in");ofstream fout("money.out");long long money[25 + 1][10000 + 1];long long shit[10000 + 1];int main() {fin>>V>>N;int coins[25];int i = 0, j = 0;//read datafor(i = 0; i < V; i++) fin>>coins[i];//初始情况for(int i = 0; i <= V; i++) {money[i][0] = 1;shit[0] = 1;} //二维数组//for(i = 1; i <= V; i++) {//for(j = 1; j <= N; j++)//if(j >= coins[i - 1])//money[i][j] = money[i - 1][j] + money[i][j - coins[i - 1]];//else//money[i][j] = money[i - 1][j];//} //一维数组for(i = 1; i <= V; i++)for(j = coins[i - 1]; j <= N;  j++) {shit[j] += shit[j - coins[i - 1]];}//fout<<money[V][N]<<endl;fout<<shit[N]<<endl;fin.close();fout.close();return 0;}









-------------------------------------------------------------------------
原题:

The cows have not only created their own government but they have chosen to create their own money system. In their own rebellious way, they are curious about values of coinage. Traditionally, coins come in values like 1, 5, 10, 20 or 25, 50, and 100 units, sometimes with a 2 unit coin thrown in for good measure.

The cows want to know how many different ways it is possible to dispense a certain amount of money using various coin systems. For instance, using a system of {1, 2, 5, 10, ...} it is possible to create 18 units several different ways, including: 18x1, 9x2, 8x2+2x1, 3x5+2+1, and many others.

Write a program to compute how many ways to construct a given amount of money using supplied coinage. It is guaranteed that the total will fit into both a signed long long (C/C++) and Int64 (Free Pascal).

PROGRAM NAME: money

INPUT FORMAT

The number of coins in the system is V (1 <= V <= 25).

The amount money to construct is N (1 <= N <= 10,000).Line 1:Two integers, V and NLines 2..:V integers that represent the available coins (no particular number of integers per line)

SAMPLE INPUT (file money.in)

3 101 2 5

OUTPUT FORMAT

A single line containing the total number of ways to construct N money units using V coins.

SAMPLE OUTPUT (file money.out)

10
原创粉丝点击