编程之美 1.6买书问题
import java.util.*; public class Test{ public static void main(String[] args) { int singlePrice=8; double[] discounts={1,0.95,0.9,0.8,0.75}; int[] nums={2,2,2,1,1}; Arrays.sort(nums); int max=nums[4]; double[][][][][] dp=new double[max+1][max+1][max+1][max+1][max+1]; for(int i=1;i<=max;i++){ for(int j=0;j<=i;j++){ for(int k=0;k<=j;k++){ for(int l=0;l<=k;l++){ for(int m=0;m<=l;m++){ if(m>=1){ if(dp[i][j][k][l][m]==0 || dp[i][j][k][l][m]>dp[i-1][j-1][k-1][l-1][m-1]+5*discounts[4]*singlePrice){ dp[i][j][k][l][m]=dp[i-1][j-1][k-1][l-1][m-1]+5*discounts[4]*singlePrice; } } if(l>=1){ int[] temp=new int[5]; temp[0]=i-1; temp[1]=j-1; temp[2]=k-1; temp[3]=l-1; temp[4]=m; Arrays.sort(temp); if(dp[i][j][k][l][m]==0 || dp[i][j][k][l][m]>dp[temp[4]][temp[3]][temp[2]][temp[1]][temp[0]]+4*discounts[3]*singlePrice){ dp[i][j][k][l][m]=dp[temp[4]][temp[3]][temp[2]][temp[1]][temp[0]]+4*discounts[3]*singlePrice; } } if(k>=1){ int[] temp=new int[5]; temp[0]=i-1; temp[1]=j-1; temp[2]=k-1; temp[3]=l; temp[4]=m; Arrays.sort(temp); if(dp[i][j][k][l][m]==0 || dp[i][j][k][l][m]>dp[temp[4]][temp[3]][temp[2]][temp[1]][temp[0]]+3*discounts[2]*singlePrice){ dp[i][j][k][l][m]=dp[temp[4]][temp[3]][temp[2]][temp[1]][temp[0]]+3*discounts[2]*singlePrice; } } if(j>=1){ int[] temp=new int[5]; temp[0]=i-1; temp[1]=j-1; temp[2]=k; temp[3]=l; temp[4]=m; Arrays.sort(temp); if(dp[i][j][k][l][m]==0 || dp[i][j][k][l][m]>dp[temp[4]][temp[3]][temp[2]][temp[1]][temp[0]]+2*discounts[1]*singlePrice){ dp[i][j][k][l][m]=dp[temp[4]][temp[3]][temp[2]][temp[1]][temp[0]]+2*discounts[1]*singlePrice; } } if(i>=1){ int[] temp=new int[5]; temp[0]=i-1; temp[1]=j; temp[2]=k; temp[3]=l; temp[4]=m; Arrays.sort(temp); if(dp[i][j][k][l][m]==0 || dp[i][j][k][l][m]>dp[temp[4]][temp[3]][temp[2]][temp[1]][temp[0]]+singlePrice){ dp[i][j][k][l][m]=dp[temp[4]][temp[3]][temp[2]][temp[1]][temp[0]]+singlePrice; } } } } } } } System.out.println(dp[nums[4]][nums[3]][nums[2]][nums[1]][nums[0]]); } }