poj2955 Brackets 简单区间dp

来源:互联网 发布:阿里云 幕布申请 编辑:程序博客网 时间:2024/05/18 18:55
// poj2955 简单区间dp// d[i][j]表示i到j区间所能形成的最大匹配序列// dp[i][j] = max(dp[i][k]+dp[k+1][j]){i<k<j}// dp[i][j] = max(dp[i+1][j-1]+2) if (s[i] match s[j])//// 记忆化搜索的时候,将dp[i][i] = 0 ,其他赋值成-1;//// 做题的时候刚开始将dp[i][j]弄成0了,结果一直tle// 最后发现有好多的状态重复计算了,所以会tle// 这题思路不难,学到了初始边界的重要性!// 继续练吧。。。。#include <algorithm>#include <bitset>#include <cassert>#include <cctype>#include <cfloat>#include <climits>#include <cmath>#include <complex>#include <cstdio>#include <cstdlib>#include <cstring>#include <ctime>#include <deque>#include <functional>#include <iostream>#include <list>#include <map>#include <numeric>#include <queue>#include <set>#include <stack>#include <vector>#define ceil(a,b) (((a)+(b)-1)/(b))#define endl '\n'#define gcd __gcd#define highBit(x) (1ULL<<(63-__builtin_clzll(x)))#define popCount __builtin_popcountlltypedef long long ll;using namespace std;const int MOD = 1000000007;const long double PI = acos(-1.L);template<class T> inline T lcm(const T& a, const T& b) { return a/gcd(a, b)*b; }template<class T> inline T lowBit(const T& x) { return x&-x; }template<class T> inline T maximize(T& a, const T& b) { return a=a<b?b:a; }template<class T> inline T minimize(T& a, const T& b) { return a=a<b?a:b; }const int maxn = 128;char s[maxn];int d[maxn][maxn];int n;void init(){memset(d,-1,sizeof(d));n = strlen(s);}bool match(char a,char b){if (a=='('&&b==')')return true;if (a=='['&&b==']')return true;return false;}int dp(int x,int y){if (x>=y)return d[x][y]=0;if (d[x][y]>=0)return d[x][y];//d[x][y] = 0;int& ans = d[x][y];ans = 0;if (match(s[x],s[y]))ans = max(ans,dp(x+1,y-1) + 2);for (int i = x;i<y;i++)ans = max(ans,dp(x,i)+dp(i+1,y));return ans;}void solve(){printf("%d\n",dp(0,n-1));}int main() {//freopen("G:\\Code\\1.txt","r",stdin);while(gets(s)){if (s[0]=='e')break;init();solve();}return 0;}

0 0
原创粉丝点击