码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 2955 Brackets 区间dp

时间:2017-02-28 00:47:00      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:namespace   end   bool   images   情况   ifd   close   std   strlen   

http://poj.org/problem?id=2955

区间dp的写法还是dfs的好写。

设dp[i][j]表示[i, j]这个区间的合法情况的最大值。

然后想要求[i, j]合法情况的最大值,有两种。

1、如果i和j的搭配的括号,那么dp[i][j] = dp[i + 1][j - 1] + 2;

2、同时还可能是分开区间,合并后才更大,例如:()()

dp[i][j] = max(dp[i][j], dp[i][k] + dp[k  + 1][j]);

技术分享
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <assert.h>
#define IOS ios::sync_with_stdio(false)
using namespace std;
#define inf (0x3f3f3f3f)
typedef long long int LL;


#include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <bitset>
const int maxn = 1e2 + 20;
char str[maxn];
char op[maxn];
int dp[maxn][maxn];
bool match(char ch1, char ch2) {
    if (ch1 == ( && ch2 == )) return true;
    if (ch1 == [ && ch2 == ]) return true;
    return false;
}
int vis[maxn][maxn], DFN;
int dfs(int be, int en) {
    if (be >= en) return 0;
    if (vis[be][en] == DFN) return dp[be][en];
    vis[be][en] = DFN;
    if (match(str[be], str[en])) dp[be][en] = dfs(be + 1, en - 1) + 2;
    for (int k = be; k <= en; ++k) {
        dp[be][en] = max(dp[be][en], dfs(be, k) + dfs(k + 1, en));
    }
    return dp[be][en];
}

void work() {
    DFN++;
    memset(dp, 0, sizeof dp);
    int lenstr = strlen(str + 1);
    cout << dfs(1, lenstr) << endl;
}


int main() {
#ifdef local
    freopen("data.txt", "r", stdin);
//    freopen("data.txt", "w", stdout);
#endif
    op[(] = );
    op[)] = (;
    op[[] = ];
    op[]] = [;
    while (scanf("%s", str + 1) && str[1] != e) work();
    return 0;
}
View Code

 

POJ 2955 Brackets 区间dp

标签:namespace   end   bool   images   情况   ifd   close   std   strlen   

原文地址:http://www.cnblogs.com/liuweimingcprogram/p/6476881.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!