现有装箱表declare T table (name varchar(10),volume decimal(9,2))insert T select '1','6.24'
union select '3','8.96'
union select '4','8.10'
union select '5','4.37'
union select '6','10.56'
union select '7','50.89'
...
union select '120','21.69'
...name是货名,volume是货物的体积
表T中有N行货物,实际数在100左右
运输货物的集装箱为68立方米
要求:用存储过程实现的算法来输出一份最大限度利用集装箱空间的货物单

解决方案 »

  1.   

    伪代码:
     tab1 (name,result,margin)  
     tab2 (name)  --记录已经使用过的记录declare
      v_max  float ;
      v_min  float ;
      v_total folat :=68 ;
      v_result varchar2(200);
      v_name   t.name%type ;
      v_flag   t.name%type ;  
    begin
     select min(volume) into v_min from t;
     for i in 1..100 loop  --假设有100行货物记录
       v_margin := v_total ;
       execute immediate 'truncate table tab2';
       if v_flag is not null then 
         insert into tab2(name) vales (v_flag) ;
         commit ;
       end if ;
       v_flag := null ;
       while v_margin>=v_min loop 
         select max(volume) into v_max from t
         where volume<=v_margin
         and name not in (select name from tab2);     /*每个货物只能使用一次*/
         
         v_margin := v_margin - v_max ;
         begin
            select name into v_name from t where volume=v_max;
            if v_flag is not null then 
                v_flag := v_name ;
            end if ;
            v_result := v_result||','||v_name;
            insert into tab2(name) values (v_name) ;
            commit ;
         exception
              when others then 
                 null ;
         end ;
       end loop ;
       insert into tab1(name,result,margin) values (v_name,v_result,v_margin);
       commit;
     end loop ;
    end ;
    最后tab1中margin最小的记录对应的result就是最佳组合。其实就是个贪婪算法的变通。这个算法是否正确