[Section] DP first POJ 2955 Brackets

WOMEN 2955 Brackets 

If s [st] == ​​s [ed], then dp [st] [ed] = dp [st + 1] [ed - 1] + 2. (This enumeration is placed before break) actually think indeed the case, the two ends are equal, then on to the head dp is initialized to the value of the substring to the middle tail plus 2

And then began to enumerate the breakpoint update dp as large as possible, large range equal to the sum between two cells

General Procedure section DP of:

Enumeration length

Enumeration starting point

Enumeration breakpoint (updated dp)

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <limits>
#include <set>
#include <queue>
#include <vector>
#include <stack>
#include <map>
#define INF 0x3f3f3f3f

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxN = 100 + 5;

string s;
int dp[maxN][maxN];
void init()
{
    memset(dp, 0, sizeof(dp));
}
int main()
{
    while(cin >> s)
    {
        if(s == "end")
            break;
        int n = s.size();
        init();
        for(int len = 2; len <= n; len ++ )//枚举长度
        {
            for(int st = 0; st < n; st ++ )//枚举起点
            {
                int ed = st + len - 1;
                if(ed >= n) break;
                int add = 0;
                if(s[st] == '(' && s[ed] == ')')
                    add ++;
                if(s[st] == '[' && s[ed] == ']')
                    add ++;
                if(add)
                    dp[st][ed] = dp[st + 1][ed - 1] + 2;
                for(int mid = st; mid <= ed - 1; mid ++ )//枚举断点
                {
                    dp[st][ed] = max(dp[st][ed], dp[st][mid] + dp[mid + 1][ed]);
                }
            }
        }
        printf("%d\n", dp[0][n - 1]);
    }
    return 0;
}

 

Published 180 original articles · won praise 54 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44049850/article/details/103865465