java 用于以最佳方式切割资源的动态编程算法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 用于以最佳方式切割资源的动态编程算法相关的知识,希望对你有一定的参考价值。

import java.util.*;


/**
example for cutting a resource of length l in given denominations in an optimal way
The running time is O(numberofdenominations*l) the auxilary space complexity is order of length

There is possibbly some amount of resource left unused depending on denominations.

You can play with denominations.
*/

public class CuttingRod{

  static RodDenomination [] denominations = {
    // new RodDenomination(1,2),
    new RodDenomination(2,5),
    new RodDenomination(3,7),
    new RodDenomination(4,8),
    new RodDenomination(18,49)
  };

  public static void main(String... args){
    for(int i = 5 ; i < 20 ; i++){
      ResourcePartitioning partitioning = maxValueOfPiece(denominations, i);
      System.out.println("Max value of length " + i + " is "+partitioning.totalValue+
      ". Pieces are " + partitioning.partLengths);
    }
  }

  public static ResourcePartitioning maxValueOfPiece(RodDenomination[] denominations , int length){
    ResourcePartitioning partitioning = new ResourcePartitioning();
    int [] bestVal = new int[length+1];//best value attainable by the length
    int [] prev = new int[length+1];//pointer to the length of remaining piece after cut
    for(int i = 0 ; i <= length ; i ++)
    {
      for(RodDenomination d : denominations){
        int reach =i+ d.length;// the next point
        if(reach <= length &&  bestVal[i] + d.value > bestVal[reach]){
          bestVal[reach] = bestVal[i] + d.value;
          prev[reach] = i;
        }
      }
    }
    partitioning.totalValue = bestVal[length];
    while(bestVal[length ] > 0){
      int biggerPiece = prev[length];
      partitioning.partLengths.add(length - biggerPiece);
      length = biggerPiece;
    }
    return partitioning;
  }

  private static class ResourcePartitioning{
    int totalValue;
    List<Integer> partLengths = new ArrayList<>();
  }

  private static class RodDenomination{
    int length;
    int value;
    private RodDenomination(int length , int val){
      this.length = length;
      value = val;
    }
  }

}

以上是关于java 用于以最佳方式切割资源的动态编程算法的主要内容,如果未能解决你的问题,请参考以下文章

动态编程 - 杆切割自下而上算法(CLRS)解决方案不正确?

你在Java中用过动态规划吗?

《算法导论》中动态规划求解钢条切割问题

连续分配管理方式的动态分区分配算法(首次适应最佳适应最坏适应邻接适应算法)

连续分配管理方式的动态分区分配算法(首次适应最佳适应最坏适应邻接适应算法)

单击事件不适用于以编程方式/动态创建的选项按钮