문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top