繁体   English   中英

寻找动态编程解决方案

[英]Looking for dynamic programming solution

我有以下问题:

给出了一个字符串(其中没有空格)。 我还有一个cost函数,该函数返回字符串的成本(通过将字符串中每个单词的评估成本相加而构建)。 实际上,它使用字典并评估编辑距离。

我的程序需要插入空格(尽可能少)以获得最佳的全局成本。

我想要原始算法,优化会更进一步。

例:

errorfreesampletext->无错误的示例文本
scchawesomeness->这样的令人敬畏

我认为这应该有效。

dp[i] = minimum cost if we consider only the first i characters

for i = 1 to n do
  dp[i] = cost(a[1, i]) // take sequence [1, i] without splitting it
  for k = 1 to i - 1 do
    dp[i] = min(dp[i], dp[k] + cost(a[k + 1, i])) // see if it's worth splitting 
                                                  // sequence [1, i] into
                                                  // [1, k] and [k + 1, i]

这是一个算法。 它可能不是最有效的,但我能想到的是最好的。

Input:
   A string of length n
   A list of words
Create a lookup table:
   Create a grid M of n x n slots. (1..n, 1..n)
   Create a grid W of n x n slots. (1..n, 1..n)
   For each starting position i in 1..n:
      For each ending position j in i..n:
         For each word w:
            Find the edit distance d between w and substring (i..j)
            If d is less than M[i,j]:
               Set M[i,j] to d
               Set W[i,j] to w
Find the best words for each position:
   Create a list L of (n+1) slots. (0..n)
   Create a list C of (n+1) slots. (0..n)
   Set L[0] to 0
   For each ending position i in 1..n:
      Set L[i] to infinity
      For each starting position j in 0..i-1:
         If L[j] + M[i,j] is less than L[i]:
            Set L[i] to L[j] + M[i,j]
            Set C[i] to j
Create the final result string:
   Create a list R
   Let i be the length of the input (n)
   Repeat while i > 0:
      Let j be C[i]
      Prepend W[j,i] to R
      Set i to j-1
   Return R

该算法分为三个阶段:

  1. 第一阶段计算查找表。 M是将任何单词放入子串i .. j的最佳成本。 W是与该成本相关的词。 3 ) ( n = input length, w = maximum word length, and m = word count) O 3 )( n =输入长度, w =最大字长, m =字数)

  2. 第二阶段为每个职位找到最佳词汇。 L是直到位置i的最佳总成本。 C是与该费用相关的最后一个单词的起始位置。 2 ) O 2

  3. 最后阶段组装最终的字符串。 R是与输入字符串匹配时成本最低的单词列表。 ). O )。

第一阶段是最昂贵的。 应该可以将其削减一个数量级,但是我不知道如何做到。 您也可以将其与阶段2结合使用,但不会从中获得太多收益。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM