codevs 3657 括号序列

dp[i][j]表示i到j需要添加的长度

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<queue>
 5 #include<stack>
 6 using namespace std;
 7 #define LL long long
 8 #define clc(a,b) memset(a,b,sizeof(a))
 9 #define inf 0x3f3f3f3f
10 const int maxn=20010;
11 char s[1010];
12 // int ans;
13 int dp[1010][1010];
14 int used[1010][1010];
15 int dfs(int x,int y){
16    int ans=inf;
17     if(used[x][y]) return dp[x][y];
18     if(x>y) return 0;
19     if(x==y) return 1;
20     else 
21     {
22        if((s[x]=='('&&s[y]==')')||(s[x]=='['&&s[y]==']'))
23         ans=min(ans,dfs(x+1,y-1));
24        if(s[x]=='('||s[x]=='[')
25         ans=min(ans,dfs(x+1,y)+1);
26        if(s[y]==')'||s[y]==']')
27         ans=min(ans,dfs(x,y-1)+1);
28        for(int i=x;i<y;i++){
29         ans=min(ans,dfs(x,i)+dfs(i+1,y));
30     }
31     }
32     dp[x][y]=ans;
33     used[x][y]=1;
34     return dp[x][y];
35 }
36 int main(){
37     while(scanf("%s",s)!=EOF){
38         // ans=-inf;
39         clc(dp,-1);
40         clc(used,0);
41         int ans=dfs(0,strlen(s)-1);
42         printf("%d\n",ans);
43     }
44     return 0;
45 }
View Code

 

posted @ 2016-04-15 20:23  yyblues  阅读(287)  评论(0编辑  收藏  举报