数据结构之贪心算法(背包问题的思考)
来源:互联网 发布:matlab2014b mac 编辑:程序博客网 时间:2024/06/06 14:24
- package com.lip.datastructure;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public class Pack
- {
-
- public static void main(String[] args)
- {
-
- int []weight={8,7,5,4,4,3,3,2,2,2,1};
- int []box={12,12,12,10};
- int []result=loadInBox(Type.OFFLINE, box, weight);
-
- for(int i=0;i<box.length;i++)
- {
- System.out.println("第"+(i+1)+"号箱子货物:");
- print(weight, result, i+1);
- System.out.println();
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
-
-
-
-
-
-
-
- public static int[]loadInBox(Type type,int box[],int []weight)
- {
- int []result=new int[weight.length];
- Sort.quickSort(weight);
- int sum=0;
- for(int i=0;i<weight.length;i++)
- sum+=weight[i];
- int sum2=0;
- for(int i=0;i<box.length;i++)
- sum2+=box[i];
- if(sum>sum2)
- return null;
- if(type==Type.OFFLINE)
- {
- for(int i=weight.length-1,j=0;i>-1;i--)
- {
- int find=box.length;
- while(weight[i]>box[j])
- {
- j=(j+1)%box.length;
- find--;
- if(find==0)
- {
- System.out.println("------背包不够---------");
- return null;
- }
- }
- result[i]=j+1;
- box[j]-=weight[i];
- j=(j+1)%box.length;
- }
- }
- else if(type==Type.ONLINE)
- {
- for(int i=0;i<box.length;i++)
- {
-
- for(int j=weight.length-1;j>-1;j--)
- {
- if(box[i]==0)
- break;
- if(result[j]==0&&weight[j]<=box[i])
- {
- box[i]-=weight[j];
- result[j]=i+1;
- }
- }
- }
- }
- return result;
- }
- public static void print(int []weight,int []result,int k)
- {
- for(int i=0;i<result.length;i++)
- if(result[i]==k)
- System.out.print(weight[i]+" ");
- }
-
-
-
-
-
-
-
- public enum Type
- {
- ONLINE,OFFLINE;
- };
-
-
-
-
-
-
-
-
-
-
-
-
- public static int[] loadInPack(int c,int[]value,int []weight)
- {
-
- double []price=new double[value.length];
- int []position=new int[value.length];
- int p=0;
- for(int i=0;i<value.length;i++)
- price[i]=(double)value[i]/weight[i];
-
- while(c>0)
- {
- double max=-1;
- int pos=-1;
- for(int i=0;i<price.length;i++)
- {
- if(price[i]!=-1&&price[i]!=0&&max<price[i])
- {
- max=price[i];
- pos=i;
- }
- }
- if(pos==-1)
- break;
- if(c>=weight[pos])
- {
- c-=weight[pos];
- price[pos]=-1;
- position[p]=pos+1;
- p++;
- }
- else
- {
- price[pos]=0;
- }
- }
-
- return position;
-
- }
- }
贪婪算法运行效果:
脱机装箱:
联机装箱:
贪心算法解决0-1背包问题: