JAVA算法:把一块木板切成正方形的最低成本—动态规划
给出了一块长度为m宽度为n的木板,需要把这个木板分解成m*n的正方形,这样就可以把破坏的成本降到最低。
每边的切割成本将为板提供。简言之,我们需要选择这样一个切割的顺序,以使成本最小化。
对于上述板,切割成正方形的最佳方法是:最低总成本为42。
使用以下步骤:
Initial Value : Total_cost = 0
Total_cost = Total_cost + edge_cost * total_pieces
成本4水平切割成本=0+4*1=4
成本4垂直切割成本=4+4*2=12
成本3垂直切割成本=12+3*2=18
成本2水平切割成本=18+2*3=24
成本2垂直切割成本=24+2*3=30
成本1水平切割成本=30+1*4=34
成本1垂直切割成本=34+1*4=38
成本1垂直切割成本=38+1*4=42
问题分析:
这个问题可以用贪心算法来解决。
如果总成本用s表示,那么s=a1w1+a2w2…+akwk,其中wi是某一切边的成本,ai是相应的系数,系数ai是由我们在切边过程结束时用wi竞争的切边总数决定的。
请注意,系数之和总是常数,因此我们要找到可获得的ai的分布,这样s是最小的。为了做到这一点,我们尽可能早地在成本最高的边缘进行切割,这将达到最佳的S。如果我们遇到几个成本相同的边缘,我们可以先切割其中任何一个。
下面是使用上述方法的解决方案,首先我们将切割边缘的成本按相反的顺序排序,然后将它们从较高的成本循环到较低的成本构建我们的解决方案。每次我们选择一个边缘时,计数器部件计数增加1,每次乘以相应的边缘切割成本。
注意下面使用了sort方法,发送greater()作为第三个参数,以非递增的顺序对数字排序,它是库的预定义函数。
package com.bean.algorithm.basic;
import java.util.Arrays;
import java.util.Collections;
public class MinimumCosttoCut {
// Java program to divide a
// board into m*n squares
// method returns minimum cost to break board into
// m*n squares
static int minimumCostOfBreaking(Integer X[], Integer Y[], int m, int n) {
int res = 0;
// sort the horizontal cost in reverse order
Arrays.sort(X, Collections.reverseOrder());
// sort the vertical cost in reverse order
Arrays.sort(Y, Collections.reverseOrder());
// initialize current width as 1
int hzntl = 1, vert = 1;
// loop untill one or both
// cost array are processed
int i = 0, j = 0;
while (i < m && j < n) {
if (X[i] > Y[j]) {
res += X[i] * vert;
// increase current horizontal
// part count by 1
hzntl++;
i++;
} else {
res += Y[j] * hzntl;
// increase current vertical
// part count by 1
vert++;
j++;
}
}
// loop for horizontal array,
// if remains
int total = 0;
while (i < m)
total += X[i++];
res += total * vert;
// loop for vertical array,
// if remains
total = 0;
while (j < n)
total += Y[j++];
res += total * hzntl;
return res;
}
// Driver program
public static void main(String arg[]) {
int m = 6, n = 4;
Integer X[] = { 2, 1, 3, 1, 4 };
Integer Y[] = { 4, 1, 2 };
System.out.print(minimumCostOfBreaking(X, Y, m - 1, n - 1));
}
}
运行结果:
42