Dollar Dayz POJ - 3181(动态规划+大数高低位分离输出)
?
題意:就是給出二個數N,和k,有1~k種錢幣,每種都 是無限個,用這些種類的錢幣可以組合成總錢N有多少種方式。
解題:這就是一個完全背包,把N看成容量,錢幣的類型值為 花費和價值。與記錄有多少種路徑的走法一樣,但要注意的是 這里輸出的數據會很大,會超出long long型,所以用兩個 long long 型來表示一個大數。分別是高位和低位,低位不 超過10^18,也就是有17位數。
Time limit? ? 1000 ms
Memory limit? ? ?65536 kB
OS? ? ? Linux
Source? ? ? ? ?USACO 2006 January Silver
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$21 @ US$3 + 2 @ US$11 @ US$2 + 3 @ US$12 @ US$2 + 1 @ US$15 @ US$1Write 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).
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 3Sample Output
5 題意:就是給出二個數N,和k,有1~k種錢幣,每種都 是無限個,用這些種類的錢幣可以組合成總錢N有多少種方式。 解題:這就是一個完全背包,把N看成容量,錢幣的類型值為 花費和價值。與記錄有多少種路徑的走法一樣,但要注意的是 這里輸出的數據會很大,會超出long long型,所以用兩個 long long 型來表示一個大數。分別是高位和低位,低位不 超過10^18,也就是有17位數。數據較弱可不對低位為零數位補充分析
#include<iostream> #include<algorithm> #include<string.h> using namespace std; const long long M=100000000000000000; int m,n; long long dp[10010],u[10010];/*用dp數組記錄19位以上的數,u數組記錄19位以下的數*/ int main() {while(cin>>m>>n){memset(dp,0,sizeof(dp));u[0]=1;for(int i=1; i<=n; i++)for(int j=i; j<=m; j++){dp[j]+=dp[j-i];u[j]+=u[j-i];if(u[j]>=M){dp[j]+=u[j]/M;u[j]%=M;}}if(dp[m])cout<<dp[m];cout<<u[m]<<endl;}return 0; }較精準代碼
#include<iostream> #include<algorithm> #include<string.h> using namespace std; const long long M=100000000000000000; int m,n; long long dp[10010],u[10010];/*用dp數組記錄19位以上的數,u數組記錄19位以下的數*/ int main() {while(cin>>m>>n){memset(dp,0,sizeof(dp));u[0]=1;for(int i=1; i<=n; i++)for(int j=i; j<=m; j++){dp[j]+=dp[j-i];u[j]+=u[j-i];if(u[j]>=M){dp[j]+=u[j]/M;u[j]%=M;}}long long ans=u[m];int sum=0;while(ans)/*可能出現低位位數不夠的問題,故加零*/{sum++;ans/=10;}if(dp[m]){cout<<dp[m];while(sum<17){sum++;cout<<"0";}}cout<<u[m]<<endl;}return 0; } /*題目意思:就是給出二個數N,和k,有1~k種錢幣,每種都 是無限個,用這些種類的錢幣可以組合成總錢N有多少種方式。*/ /*解題:這就是一個完全背包,把N看成容量,錢幣的類型值為 花費和價值。與記錄有多少種路徑的走法一樣,但要注意的是 這里輸出的數據會很大,會超出long long型,所以用兩個 long long 型來表示一個大數。分別是高位和低位,低位不 超過10^18,也就是有17位數。 */?
總結
以上是生活随笔為你收集整理的Dollar Dayz POJ - 3181(动态规划+大数高低位分离输出)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Pearls POJ - 1260(区间
- 下一篇: A Mini Locomotive PO