做了好多题都遇到0-1背包,这次也终于做了一次真正的0-1背包问题。
并且又练了一种排序,选择排序,确切得说是二元选择排序,是对选择排序的优化。
第一步读入数据,读入的过程中要将不符合条件的数据剔除。第二步,对发票总额排序。第三步,用0-1背包解决。
代码:
package Test1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
public class Test44_1025 {
/**
* by qr jobdu 1025 2014-8-24
* @throws IOException
*/
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true){
String str=br.readLine();
String temp[]=str.split(" ");
double Q=Double.parseDouble(temp[0]);
int N=Integer.parseInt(temp[1]);
if(N==0)
break;
double totamo[]=new double[N]; //totalamount
for(int i=0;i<N;i++){
str=br.readLine();
temp=str.split(" ");
int n=Integer.parseInt(temp[0]);
for(int j=1;j<=n;j++){
int index=temp[j].indexOf(":");
String category=temp[j].substring(0,index);
boolean flag=false; //标记是否要跳出循环 不为ABC,大于600和1000,三个条件跳出
if(category.equals("A") || category.equals("B") || category.equals("C")){
double money=Double.parseDouble(temp[j].substring(index+1));
if(money<=600.00)
totamo[i]+=money;
else
flag=true;
}else {
flag=true;
}
if(flag){
totamo[i]=0;
break;
}
}
if(totamo[i]>Q || totamo[i]>1000.00){
totamo[i]=0;
}
}
selectsort(totamo,N);
//0-1背包
double max=count(totamo,0,N,Q);
System.out.println(new BigDecimal(max).setScale(2,BigDecimal.ROUND_HALF_UP));
/*
问题定位:0-1背包问题
可能的错误,误用贪心算法求解,应该使用动态规划。这里给出一个测试用例:
100.00 3
1 A:80.00
1 B:70:00
1 C:30:00
使用贪心算法得到的是80.00,最优解应该是100.00
*/
}
}
//第i个物品 背包中剩余重量为q
private static double count(double totamo[],int i, int n,double q) { //0-1背包,用递归求解
if(i>=n || totamo[i]==0)
return 0;
if(q>=totamo[i])
return Math.max(count(totamo,i+1,n,q), count(totamo,i+1,n,q-totamo[i])+totamo[i]); //0-1 放入背包和不放入背包 选大的那个
else
return count(totamo,i+1,n,q);
}
private static void selectsort(double[] arr, int n) { //二元选择排序(改进选择排序) 从大到小 i和n-1-i是对称的
int m=n/2;
for(int i=0;i<m;i++){
// double min=arr[i]; //可以只存索引,不必存最大最小值 因为在找最大值和最小值的过程中都没有改变数组中值的操作
// double max=arr[i];
int min=i;//最小值的索引
int max=i;//最大值的索引
int k=n-1-i;
for(int j=i+1;j<=k;j++){
if(arr[j]<arr[min]){
min=j;
continue; //添加,不必再判断
}
if(arr[j]>arr[max]){
max=j;
}
}
double temp=arr[min];
arr[min]=arr[k];
arr[k]=temp;
temp=arr[max];
arr[max]=arr[i];
arr[i]=temp;
}
}
}