【九度OJ】1025【选择排序】【0-1背包】

做了好多题都遇到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;
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值