New Zealand currency consists of $100, $50, $20, $10, and $5 notes and $2, $1, 50c, 20c, 10c and 5c coins. Write a program that will determine, for any given amount, in how many ways that amount may be made up. Changing the order of listing does not increase the count. Thus 20c may be made up in 4 ways: 1 20c, 2 10c, 10c+2 5c, and 4 5c.
Input
Input will consist of a series of real numbers no greater than $50.00 each on a separate line. Each amount will be valid, that is will be a multiple of 5c. The file will be terminated by a line containing zero (0.00).
Output
Output will consist of a line for each of the amounts in the input, each line consisting of the amount of money (with two decimal places and right justified in a field of width 5), followed by the number of ways in which that amount may be made up, right justified in a field of width 12.
Sample input
0.20 2.00 0.00
Sample output
0.20 4 2.00 293
刚开始拿到这道题时,想到的是老师课堂上讲过的整数划分问题 所以就尝试着用递归的方法去解决,但是在跑出来的结果会莫名的少了一些划分情况,在加断点调试了之后才发现是小数相减之后的精度问题导致一些情况没有被累加到,通过神奇地度娘知道了用BigDecimal来解决 一下便是我的代码
package acm; import java.util.*; import java.math.BigDecimal; public class Dollars{ static double[] money=new double[]{100,50,20,10,5,2,1,0.5,0.2,0.1,0.05}; static int d(double n,int i){ BigDecimal a1 = new BigDecimal(Double.toString(money[i])); BigDecimal b1 = new BigDecimal(Double.toString(n)); if(money[i]==0.05 || n==0.05) return 1; if( i>10 || n<0.05) return 0; if(n==money[i]) return 1+d(n,i+1); if(money[i]>n){ while(money[i]>n) i++; return d(n,i); } else return d(b1.subtract(a1).doubleValue(),i)+d(n,i+1); } public static void main(String args[]){ Scanner input = new Scanner(System.in); double m = input.nextDouble(); while(m!=0.0){ System.out.printf("%5.2f%12d\n",m,d(m,0)); m=input.nextDouble(); } input.close(); } }
但是 新的问题又来了 用递归调用测小数据时还好,当测试到50时,竟然好久答案还没出来 递归的效率太低在OJ上提交时也出现时TLE的问题,所以和同学交流及搜索网上资料后 采用递推的方法解决
package acm; import java.util.*; //import java.math.BigDecimal; public class Dollars{ public static void main(String args[]){ int[] money = new int[]{1,2,4,10,20,40,100,200,400,1000,2000}; int[] ans = new int[6001]; Scanner input = new Scanner(System.in); float m = input.nextFloat(); ans[0]=1; for(int i=0;i<11;i++){ for(int j=money[i];j<6001;j++){ ans[j]+=ans[j-money[i]]; } } while(m!=0.0){ System.out.printf("%5.2f%12d\n",m,ans[(int)(m/0.05)]); m=input.nextFloat(); } input.close(); } }
终于都Accepted了 不过有点无语的是不知为什么是double型的时候一直WRO 一改成float就过了 还是要多多累计经验。