poj 1141-Brackets Sequence解题报告
区间dp,dp[i][j]表示i-j所需要的最少要加的括号数,并且记录路径,输出的时候递归输出
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<string.h> 3 #define N 110 4 #define inf 0x7fffffff 5 char str[N]; 6 int dp[N][N]; 7 int path[N][N]; 8 void out(int i,int j) 9 { 10 if(i>j) 11 return; 12 if(i==j) 13 { 14 if(str[i]=='('||str[i]==')') 15 printf("()"); 16 else 17 printf("[]"); 18 } 19 else if(path[i][j]==-1) 20 { 21 printf("%c",str[i]); 22 out(i+1,j-1); 23 printf("%c",str[j]); 24 } 25 else 26 { 27 out(i,path[i][j]); 28 out(path[i][j]+1,j); 29 } 30 } 31 int main() 32 { 33 int i,j,k,len,p; 34 scanf("%s",str); 35 len=strlen(str); 36 for(i=0;i<len;i++) 37 dp[i][i]=1; 38 memset(path,-1,sizeof(path)); 39 for(p=1;p<len;p++) 40 for(i=0;i<len-p;i++) 41 { 42 j=i+p; 43 dp[i][j]=inf; 44 if((str[i]=='('&&str[j]==')')||(str[i]=='['&&str[j]==']')&&dp[i][j]>dp[i+1][j-1]) 45 { 46 dp[i][j]=dp[i+1][j-1]; 47 path[i][j]=-1; 48 } 49 for(k=i;k<j;k++) 50 { 51 if(dp[i][j]>dp[i][k]+dp[k+1][j]) 52 { 53 dp[i][j]=dp[i][k]+dp[k+1][j]; 54 path[i][j]=k; 55 } 56 } 57 } 58 out(0,len-1); 59 printf("\n"); 60 return 0; 61 }