如何理解线性分区中的动态编程解决方案?

时间:2011-10-29 12:08:46

标签: algorithm partitioning dynamic-programming

我很难理解线性分区问题的动态编程解决方案。我正在阅读Algorithm Design Manual,问题在8.5节中描述。我已经无数次阅读了这个部分,但我只是没有得到它。我认为这是一个糟糕的解释(我现在读到的内容已经好多了),但是我还没有能够很好地理解这个问题以寻找替代解释。欢迎链接到更好的解释!

我找到了一个与该书类似的文章页面(可能来自本书的第一版):The Partition Problem

第一个问题:在本书的示例中,分区从最小到最大排序。这只是巧合吗?从我所看到的,元素的排序对算法来说并不重要。

这是我对递归的理解:

让我们使用以下序列并将其分为4:

{S1...Sn} =  100   150   200   250   300   350   400   450   500
k = 4

第二个问题:这就是我认为递归将如何开始 - 我理解正确吗?

第一次递归是:

100   150   200   250   300   350   400   450 | 500 //3 partition to go
100   150   200   250   300   350   400 | 450 | 500 //2 partition to go 
100   150   200   250   300   350 | 400 | 450 | 500 //1 partition to go
100   150   200   250   300 | 350 | 400 | 450 | 500 //done

第二次递归是:

100   150   200   250   300   350   400   450 | 500 //3 partition to go
100   150   200   250   300   350   400 | 450 | 500 //2 partition to go 
100   150   200   250   300   350 | 400 | 450 | 500 //1 partition to go
100   150   200   250 | 300   350 | 400 | 450 | 500 //done

第三次递归是:

100   150   200   250   300   350   400   450 | 500 //3 partition to go
100   150   200   250   300   350   400 | 450 | 500 //2 partition to go 
100   150   200   250   300   350 | 400 | 450 | 500 //1 partition to go
100   150   200 | 250   300   350 | 400 | 450 | 500 //done

第四次递归是:

100   150   200   250   300   350   400   450 | 500 //3 partition to go
100   150   200   250   300   350   400 | 450 | 500 //2 partition to go 
100   150   200   250   300   350 | 400 | 450 | 500 //1 partition to go
100   150 | 200   250   300   350 | 400 | 450 | 500 //done

第五次递归是:

100   150   200   250   300   350   400   450 | 500 //3 partition to go
100   150   200   250   300   350   400 | 450 | 500 //2 partition to go 
100   150   200   250   300   350 | 400 | 450 | 500 //1 partition to go
100 | 150   200   250   300   350 | 400 | 450 | 500 //done

第6次递归是:

100   150   200   250   300   350   400   450 | 500 //3 partition to go
100   150   200   250   300   350   400 | 450 | 500 //2 partition to go 
100   150   200   250   300 | 350   400 | 450 | 500 //1 partition to go
100   150   200   250 | 300 | 350   400 | 450 | 500 //done

第7次递归是:

100   150   200   250   300   350   400   450 | 500 //3 partition to go
100   150   200   250   300   350   400 | 450 | 500 //2 partition to go 
100   150   200   250   300 | 350   400 | 450 | 500 //1 partition to go
100   150   200 | 250   300 | 350   400 | 450 | 500 //done

第8次递归是:

100   150   200   250   300   350   400   450 | 500 //3 partition to go
100   150   200   250   300   350   400 | 450 | 500 //2 partition to go 
100   150   200   250   300 | 350   400 | 450 | 500 //1 partition to go
100   150 | 200   250   300 | 350   400 | 450 | 500 //done

第9次递归是:

100   150   200   250   300   350   400   450 | 500 //3 partition to go
100   150   200   250   300   350   400 | 450 | 500 //2 partition to go 
100   150   200   250   300 | 350   400 | 450 | 500 //1 partition to go
100 | 150   200   250   300 | 350   400 | 450 | 500 //done

等...

以下是书中出现的代码:

partition(int s[], int n, int k)
{
    int m[MAXN+1][MAXK+1];                  /* DP table for values */
    int d[MAXN+1][MAXK+1];                  /* DP table for dividers */ 
    int p[MAXN+1];                          /* prefix sums array */
    int cost;                               /* test split cost */
    int i,j,x;                              /* counters */

    p[0] = 0;                               /* construct prefix sums */
    for (i=1; i<=n; i++) p[i]=p[i-1]+s[i];

    for (i=1; i<=n; i++) m[i][3] = p[i];    /* initialize boundaries */
    for (j=1; j<=k; j++) m[1][j] = s[1];


    for (i=2; i<=n; i++)                    /* evaluate main recurrence */
        for (j=2; j<=k; j++) {
            m[i][j] = MAXINT;
            for (x=1; x<=(i-1); x++) {
                cost = max(m[x][j-1], p[i]-p[x]);
                if (m[i][j] > cost) {
                    m[i][j] = cost;
                    d[i][j] = x;
                }
            }
        }

    reconstruct_partition(s,d,n,k);         /* print book partition */
}

关于算法的问题:

  1. md
  2. 中存储了哪些值
  3. '成本'是什么意思?它只是分区中元素值的总和吗?还是有一些更微妙的含义?

3 个答案:

答案 0 :(得分:35)

请注意书中对算法的解释存在一个小错误,请在errata中查找文本“(*)Page 297”。

关于您的问题:

  1. 不,这些项目不需要排序,只需连续(即不能重新排列)
  2. 我认为可视化算法的最简单方法是手动追踪reconstruct_partition程序,使用图8.8中最右边的表格作为指南
  3. 在书中,它指出m [i] [j]是“{s1,s2,...,si}的所有分区的最小可能成本”到j范围,其中分区的成本是如果你原谅滥用术语,那么它就是“其中一个部分中的元素总和”。换句话说,它是“最小和的最大值”。另一方面,d [i] [j]存储索引位置。用于为给定对i,j创建一个分区,如前面所定义
  4. 有关“费用”的含义,请参阅上一个答案
  5. 修改

    这是我对线性分区算法的实现。它基于Skiena的算法,但是以pythonic的方式;并返回分区列表。

    from operator import itemgetter
    
    def linear_partition(seq, k):
        if k <= 0:
            return []
        n = len(seq) - 1
        if k > n:
            return map(lambda x: [x], seq)
        table, solution = linear_partition_table(seq, k)
        k, ans = k-2, []
        while k >= 0:
            ans = [[seq[i] for i in xrange(solution[n-1][k]+1, n+1)]] + ans
            n, k = solution[n-1][k], k-1
        return [[seq[i] for i in xrange(0, n+1)]] + ans
    
    def linear_partition_table(seq, k):
        n = len(seq)
        table = [[0] * k for x in xrange(n)]
        solution = [[0] * (k-1) for x in xrange(n-1)]
        for i in xrange(n):
            table[i][0] = seq[i] + (table[i-1][0] if i else 0)
        for j in xrange(k):
            table[0][j] = seq[0]
        for i in xrange(1, n):
            for j in xrange(1, k):
                table[i][j], solution[i-1][j-1] = min(
                    ((max(table[x][j-1], table[i][0]-table[x][0]), x) for x in xrange(i)),
                    key=itemgetter(0))
        return (table, solution)
    

答案 1 :(得分:3)

我在PHP上实现了ÓscarLópez算法。请随时使用。

 /**
 * Example: linear_partition([9,2,6,3,8,5,8,1,7,3,4], 3) => [[9,2,6,3],[8,5,8],[1,7,3,4]]
 * @param array $seq
 * @param int $k
 * @return array
 */
protected function linear_partition(array $seq, $k)
{
    if ($k <= 0) {
        return array();
    }

    $n = count($seq) - 1;
    if ($k > $n) {
        return array_map(function ($x) {
            return array($x);
        }, $seq);
    }

    list($table, $solution) = $this->linear_partition_table($seq, $k);
    $k = $k - 2;
    $ans = array();

    while ($k >= 0) {
        $ans = array_merge(array(array_slice($seq, $solution[$n - 1][$k] + 1, $n - $solution[$n - 1][$k])), $ans);
        $n = $solution[$n - 1][$k];
        $k = $k - 1;
    }

    return array_merge(array(array_slice($seq, 0, $n + 1)), $ans);
}

protected function linear_partition_table($seq, $k)
{
    $n = count($seq);

    $table = array_fill(0, $n, array_fill(0, $k, 0));
    $solution = array_fill(0, $n - 1, array_fill(0, $k - 1, 0));

    for ($i = 0; $i < $n; $i++) {
        $table[$i][0] = $seq[$i] + ($i ? $table[$i - 1][0] : 0);
    }

    for ($j = 0; $j < $k; $j++) {
        $table[0][$j] = $seq[0];
    }

    for ($i = 1; $i < $n; $i++) {
        for ($j = 1; $j < $k; $j++) {
            $current_min = null;
            $minx = PHP_INT_MAX;

            for ($x = 0; $x < $i; $x++) {
                $cost = max($table[$x][$j - 1], $table[$i][0] - $table[$x][0]);
                if ($current_min === null || $cost < $current_min) {
                    $current_min = $cost;
                    $minx = $x;
                }
            }

            $table[$i][$j] = $current_min;
            $solution[$i - 1][$j - 1] = $minx;
        }
    }

    return array($table, $solution);
}

答案 2 :(得分:1)

以下是python中Skienna线性分割算法的改进实现,除了答案本身之外,该算法不计算最后k个列值:M [N] [K](单元格计算仅取决于前一个)

针对输入{1,2,3,4,5,6,7,8,9}(在本书的Skienna示例中使用)进行测试,得出的矩阵M略有不同(经过上述修改),但正确返回最终结果(在此示例中,将s最小成本划分为k个范围是17,并且矩阵D用于打印导致该最优值的分频器位置列表)。

import math


def partition(s, k):
    # compute prefix sums

    n = len(s)
    p = [0 for _ in range(n)]
    m = [[0 for _ in range(k)] for _ in range(n)]
    d = [[0 for _ in range(k)] for _ in range(n)]

    for i in range(n):
        p[i] = p[i-1] + s[i]

    # initialize boundary conditions
    for i in range(n):
        m[i][0] = p[i]

    for i in range(k):
        m[0][i] = s[0]

    # Evaluate main recurrence
    for i in range(1, n):
        """
          omit calculating the last M's column cells 
          except for the sought minimum cost M[N][K]
        """
        if i != n - 1:
            jlen = k - 1
        else:
            jlen = k

        for j in range(1, jlen):

            """
            - computes the minimum-cost partitioning  of the set {S1,S2,.., Si} into j partitions .
            - this part should be investigated more closely .

            """
            #
            m[i][j] = math.inf

            # This loop needs to be traced to understand it better
            for x in range(i):
                sup = max(m[x][j-1], p[i] - p[x])
                if m[i][j] > sup:
                    m[i][j] = sup
                    # record which divider position was required to achieve the value s
                    d[i][j] = x+1

    return s, d, n, k


def reconstruct_partition(S, D, N, K):
    if K == 0:
        for i in range(N):
            print(S[i], end="_")
        print(" | ", end="")
    else:
        reconstruct_partition(S, D, D[N-1][K-1], K-1)
        for i in range(D[N-1][K-1], N):
            print(S[i], end="_")
        print(" | ", end="")

# MAIN PROGRAM

S, D, N, K = partition([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)

reconstruct_partition(S, D, N, K)