poj 1141

简单的dp

忘了\n,调了半天(目测不是第一次了)

直接贴代码:

#include<cstdio>

#include<cstring>

using namespace std;

 

char s[120];

int dp[120][120]={0};

int min(int x,int y){

         return (x>y)?y:x;

}

void solve(int x,int y){

         if(dp[x][y]==0){

                   for(int i=x;i<=y;i++)

                            printf("%c",s[i]);

                   return;

         }

         if(y==x){

                   if(s[x]=='(' || s[x]==')')printf("()");

                   if(s[x]=='[' || s[x]==']')printf("[]");

                   return;

         }

         if((s[x]=='(' && s[y]==')' || s[x]=='[' && s[y]==']') && dp[x][y]==dp[x+1][y-1]){

                   printf("%c",s[x]);

                   solve(x+1,y-1);

                   printf("%c",s[y]);

                   return;

         }

         for(int i=x;i<y;i++)

                   if(dp[x][y]==dp[x][i]+dp[i+1][y]){

                            solve(x,i);

                            solve(i+1,y);

                            return;

                   }

         return;

}

int main(){

         gets(s);

         int l=strlen(s);

         for(int i=0;i<l;i++)dp[i][i]=1;

         for(int i=1;i<l;i++)

                   for(int j=0;j<l-i;j++){

                            int a=j,b=j+i;

                            dp[a][b]=200;

                            if(s[a]=='(' && s[b]==')' || s[a]=='[' && s[b]==']')dp[a][b]=dp[a+1][b-1];

                            for(int k=a;k<b;k++)

                                     dp[a][b]=min(dp[a][b],dp[a][k]+dp[k+1][b]);

                   }

/*     for(int i=0;i<l;i++){

                   for(int j=0;j<l;j++)

                            printf("%d ",dp[i][j]);

                   printf("\n");

         }*/

         solve(0,l-1);

         printf("\n");

         return 0;

}

posted @ 2013-07-01 21:48  shanquan2  阅读(227)  评论(0编辑  收藏  举报