题目:
java实现:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class BuyBook {
private final float price = 8f;
private float minTotalPrice;//最少付出的总钱数
private Integer[] arrNum;//5本书,各买多少本
private List<Integer> steps;//最小分配方案
private List<Integer> tempSteps;//中间临时最小分配方案
private enum PERCENT{//折扣
ONE(1.0f), TWO(0.95f), THREE(0.9f), FOUR(0.8f), FIVE(0.75f);
private float value = 0f;
private PERCENT(float value){
this.value = value;
}
public float value(){
return this.value;
}
public static PERCENT valueOf(int value){
switch (value) {
case 1:
return ONE;
case 2:
return TWO;
case 3:
return THREE;
case 4:
return FOUR;
case 5:
return FIVE;
default:
return null;
}
}
}
public BuyBook(Integer[] arrNum) {
if(arrNum.length != 5)
return;
this.arrNum = descSort(arrNum);
minTotalPrice = 0f;
for (int i = 0; i < arrNum.length; i++){
this.minTotalPrice += arrNum[i] * price;
}
steps = new ArrayList<Integer>();
tempSteps = new ArrayList<Integer>();
findMinPrice(arrNum, 0f);
}
private void findMinPrice(Integer[] arrNum, float total){
if(arrNum.length != 5)
return ;
if(arrNum[0] == 0){//结束条件
if(total < minTotalPrice){
this.minTotalPrice = total;
steps.clear();
steps.addAll(tempSteps);
}
tempSteps.clear();
}
Integer[] temparrNum = arrNum.clone();
float temp = 0f;
for(int i = 5; i >= 1; i--){
temp = 0f;
if(arrNum[i-1] >= 1){
tempSteps.add(i);
temp = i * price * PERCENT.valueOf(i).value;
for(int k = 0; k < 5; k++){
temparrNum[k] = arrNum[k];
if(k < i)
temparrNum[k] = arrNum[k] - 1;
}
temparrNum = descSort(temparrNum);
findMinPrice(temparrNum, total + temp);
}
}
}
/**
* 将arrNum2中元素逆序排序
* @param arrNum2
* @return
*/
private Integer[] descSort(Integer[] arrNum2) {
Arrays.sort(arrNum2, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o1 > o2? -1 : 1;
}
});
return arrNum2;
}
public static void main(String[] args) {
Integer[] Y = new Integer[]{2,2,2,1,1};
BuyBook books = new BuyBook(Y);
System.out.println(books.minTotalPrice);
for(int i = 0; i < books.steps.size(); i++){
System.out.println(books.steps.get(i));
}
}
}
输出:
51.2
4
4