poj 2955 区间dp
题意:求最大括号匹配
链接:点我
区间dp水题,但也是很经典,区间dp都是由此延伸出来的,越是基础题越是需要勤加练习
Sample Input
((())) ()()() ([]]) )[)( ([][][) end
Sample Output
6 6 4 0 6
2015-07-19:专题复习纪念
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cmath> 6 #include<queue> 7 #include<map> 8 using namespace std; 9 #define MOD 1000000007 10 const int INF=0x3f3f3f3f; 11 const double eps=1e-5; 12 typedef long long ll; 13 #define cl(a) memset(a,0,sizeof(a)) 14 #define ts printf("*****\n"); 15 const int MAXN=1005; 16 int n,m,tt; 17 char s[MAXN]; 18 int dp[MAXN][MAXN]; 19 int flag[MAXN][MAXN]; 20 int main() 21 { 22 int i,j,k; 23 #ifndef ONLINE_JUDGE 24 freopen("1.in","r",stdin); 25 #endif 26 while(gets(s)) 27 { 28 if(s[0]=='e') break; 29 int len=strlen(s); 30 for(i=0;i<len;i++) dp[i][i]=0; 31 for(int d=1;d<len;d++) 32 { 33 for(i=0;i+d<len;i++) 34 { 35 j=i+d; 36 dp[i][j]=-999999; 37 if((s[i]=='('&&s[j]==')')||(s[i]=='['&&s[j]==']')) 38 { 39 dp[i][j]=dp[i+1][j-1]+1; 40 } 41 for(k=i;k<j;k++) 42 { 43 if(dp[i][j]<dp[i][k]+dp[k+1][j]) 44 { 45 dp[i][j]=dp[i][k]+dp[k+1][j]; 46 } 47 } 48 } 49 } 50 printf("%d\n",dp[0][len-1]*2); 51 } 52 }
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cmath> 6 #include<queue> 7 #include<map> 8 using namespace std; 9 #define MOD 1000000007 10 const int INF=0x3f3f3f3f; 11 const double eps=1e-5; 12 typedef long long ll; 13 #define cl(a) memset(a,0,sizeof(a)) 14 #define ts printf("*****\n"); 15 const int MAXN=1005; 16 int n,m,tt; 17 int dp[MAXN][MAXN]; 18 int main() 19 { 20 int i,j,k; 21 #ifndef ONLINE_JUDGE 22 freopen("1.in","r",stdin); 23 #endif 24 char s[MAXN]; 25 while(scanf("%s",s)!=EOF) 26 { 27 if(s[0]=='e') break; 28 int len=strlen(s); 29 cl(dp); 30 for(int d=1;d<len;d++) 31 { 32 for(i=0;d+i<len;i++) 33 { 34 j=d+i; 35 if((s[i]=='('&&s[j]==')')||(s[i]=='['&&s[j]==']')) dp[i][j]=dp[i+1][j-1]+2; 36 for(k=i;k<=j;k++) 37 { 38 dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]); 39 } 40 } 41 } 42 printf("%d\n",dp[0][len-1]); 43 } 44 }