• 【POJ】1141 Brackets Sequence


    经典DP问题,注意输入不要使用while(xxx != EOF),否则WA,测试数据只有一组。同样的测试数据可能有多种答案。但最小长度唯一。一定不能用while,切记。

    #include <iostream>
    using namespace std;
    #include <string>
    
    #define MAXNUM 200
    #define MAXVAL 32767
    
    string match(char []);
    
    int main() {
        string regstr;
        char str[MAXNUM];
    
        cin >>str;
        regstr = match(str);
        cout <<regstr<<endl;
    
        return 0;
    }
    
    string match(char str[]) {
        string regstr[MAXNUM][MAXNUM];
        int add[MAXNUM][MAXNUM];
        int len = strlen(str);
        int i, j, k;
    
        memset(add, 0, sizeof(add));
    
        for (i=0; i<len; i++)
            for (j=i; j<len; j++)
            {
                add[i][j] = MAXVAL;
                regstr[i][j] = "";
            }
    
        for (i=len-1; i>=0; i--) {
            for (j=i; j<len; j++) {
                if (j == i) {
                    add[i][j] = 1;
                    if (str[i] == '(' || str[i] == ')')
                        regstr[i][j] = "()";
                    if (str[i] == '[' || str[i] == ']')
                        regstr[i][j] = "[]";
                } else {if (str[i] == '(' && str[j] == ')') {
                        add[i][j] = add[i+1][j-1];
                        regstr[i][j] = "(" + regstr[i+1][j-1] + ")";
                    } else if (str[i] == '[' && str[j] == ']') {
                        add[i][j] = add[i+1][j-1];
                        regstr[i][j] = "[" + regstr[i+1][j-1] + "]";
                    }
    
                    for (k=i; k<j; k++) {
                        if (add[i][k]+add[k+1][j] < add[i][j]) {
                            add[i][j] = add[i][k] + add[k+1][j];
                            regstr[i][j] = regstr[i][k] + regstr[k+1][j];
                        }
                    }
                }
            }
        }
    
        return regstr[0][len-1];
    }
  • 相关阅读:
    html
    头部标签
    ajax
    分辨率
    js 运动基础
    js DOM
    js定时器
    js数组
    js基础
    例子:js简易日历
  • 原文地址:https://www.cnblogs.com/bombe1013/p/3574777.html
Copyright © 2020-2023  润新知