Description
![Download as PDF Download as PDF](https://i-blog.csdnimg.cn/blog_migrate/2ea975a8d421ce3226c46b0946fd5932.png)
After making a purchase at a large department store, Mel's change was 17 cents. He received 1 dime, 1 nickel, and 2 pennies. Later that day, he was shopping at a convenience store. Again his change was 17 cents. This time he received 2 nickels and 7 pennies. He began to wonder ' "How many stores can I shop in and receive 17 cents change in a different configuration of coins? After a suitable mental struggle, he decided the answer was 6. He then challenged you to consider the general problem.
Write a program which will determine the number of different combinations of US coins (penny: 1c, nickel: 5c, dime: 10c, quarter: 25c, half-dollar: 50c) which may be used to produce a given amount of money.
Input
The input will consist of a set of numbers between 0 and 30000 inclusive, one per line in the input file.
Output
The output will consist of the appropriate statement from the selection below on a single line in the output file for each input value. The number m is the number your program computes, n is the input value.
There are mways to produce ncents change.
There is only 1 way to produce ncents change.
Sample input
17 11 4
Sample output
There are 6 ways to produce 17 cents change. There are 4 ways to produce 11 cents change. There is only 1 way to produce 4 cents change.
分析:
越来越多的题采用暴力求解会超时,就需要对程序进行优化,提前打表可以减少程序运算的次数,也可以解决部分超时问题。
本题的精髓在于 dp[j+c[i]]+=dp[j];就是说:
dp[14]=dp[4+c[3]]+=dp[4];
dp[14]=dp[9+c[2]]+=dp[9];
就是说当的组成方式是分开后的所有组成方式之和;
#include<stdio.h>
int n,c[5]= {1,5,10,25,50};
long long dp[31000]= {1};
int main()
{
int i,j,n;
for(i=0; i<5; i++)
for(j=0; j<31000-100; j++)
dp[j+c[i]]+=dp[j];
while(scanf("%d",&n)!=EOF)
{
if(dp[n]==1)
printf("There is only 1 way to produce %d cents change.\n",n);
else
printf("There are %lld ways to produce %d cents change.\n",dp[n],n);
}
return 0;
}