views:

72

answers:

1

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 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.

+1  A: 

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.

Petar Minchev
Can you explain Why you went for consecutive '*' sign?(for loop)
Vikas
Because the previous solution was not correct. I didn't take in account properly the precedence of *.
Petar Minchev
And the solution now is much easier to understand:)
Petar Minchev
@Petar Can you tell how to reconstruct solution?
Vikas
Done. The code is essentialy looking like the DP.
Petar Minchev