开发者

Minimize the sequence by putting appropriate operations ' DP'

Given a sequence,say, 222 We have to put a '+' or '* ' between each adjacent pair. '* ' has higher precedence over '+'

We have to o/p the string whose evaluation开发者_如何学C leads to minimum value. O/p must be lexicographically smallest if there are more than one.

inp:222

o/p: 2*2+2

Explaination:

2+2+2=6

2+2*2=6

2*2+2=6

of this 3rd is lexicographically smallest.

I was wondering how to construct a DP solution for this.


Let DP[N] be the smallest value we can obtain using the first N elements. I will do a recursive implementation(using memoization) with pseudocode:

int solve(int index)
{
   if (index == N)
      return 0;

   if (DP[index] already computed) 
      return DP[index];

   int result = INFINITELY LARGE NUMBER;

   //put a + sign
   result = min(result, input[index] + solve(index + 1));

   //put consecutive * signs
   int cur = input[index];
   for (int i = index + 1; i < N; i++)
   {
       cur *= input[i];
       result = min(result, cur + solve(i + 1));          
   }

   return DP[index] = result;
}

Call it with solve(0);

You can easily reconstruct the solution after this. I haven't tested it and maybe I have missed an edge case in the pseudocode but it should give you the right track.

string reconstruct(int index)
{
    if (index == N)
       return "";

    string result = "";

    //put consecutive * signs
    int cur = input[index]; 
    string temp = ToString(input[index]);
    for (int i = index + 1; i < N; i++)
    {           
        cur *= input[i];
        temp += "*";

        if (DP[index] == cur + DP[i + 1])
           result = temp + reconstruct(i + 1);
    }

    //put a + sign
    if (result == "") 
       result = ToString(input[index]) + "+" + reconstruct(index + 1);

    return result;
}

string result = reconstruct(0);

P.S Sorry for the many edits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜