Vijos-p1332 largest parenthesis (interval dp + greedy)

Largest parenthesis

description

Give a formula with N terms, 1<=N<=10. For example:
1 + 4-2-1 + 10-6
Different ways of adding brackets can get different values, and find the maximum value that can be obtained.

format

Input format

The first line is N. In the next N lines, each line is an integer, and the absolute value does not exceed 100. A positive number indicates that the preceding symbol is "+", and a negative number indicates that the preceding symbol is "-".

Output format

Output: the maximum value that can be obtained.

Example 1

Sample input 1

6
1
4
-2
-1
10
-6

Sample output 1

20

limit

1 second

prompt

1 + 4 - (2 - (1 + 10) - 6) = 20

Problem solving

Insert picture description here

Code

#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 11;
int a[maxn];
int Max[maxn][maxn];  //区间[i, j]的最大值, 不算i前面的符号时
int Min[maxn][maxn];  //区间[i, j]的最小值, 不算i前面的符号时

// 将区间[i, j]划分为子区间[i, k] 和 [k + 1, j]
// 由于k, k + 1之间的符号为负或者正,
// 因此子区间只能是该区间的最大值或最小值
// 必须从后往前遍历

int main() {
    
    
    int N;
    cin >> N;
    memset(Max, -0x3f, sizeof(Max));
    memset(Min, 0x3f, sizeof(Min));
    for (int i = 1; i <= N; i++) {
    
    
        cin >> a[i];
        Max[i][i] = Min[i][i] = abs(a[i]);
    }
    Max[0][0] = Min[0][0] = 0;

    for (int i = N - 1; i >= 0; i--) {
    
    
        for (int j = i; j <= N; j++) {
    
    
            for (int k = i; k < j; k++) {
    
    
                if (a[k + 1] >= 0) {
    
    
                    Max[i][j] = max(Max[i][j], Max[i][k] + Max[k + 1][j]);
                    Min[i][j] = min(Min[i][j], Min[i][k] + Min[k + 1][j]);
                } else {
    
    
                    Max[i][j] = max(Max[i][j], Max[i][k] - Min[k + 1][j]);
                    Min[i][j] = min(Min[i][j], Min[i][k] - Max[k + 1][j]);
                }
            }
        }
    }

    cout << Max[0][N] << endl;

    system("pause");
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/109608088