[DP]hit1603
http://acm.hit.edu.cn/hoj/problem/view?id=1603
备忘录式dp,然后递归输出结果:
#include<iostream> #include<cstdio> #include<iomanip> #include<algorithm> #include<cstring> #include<vector> using namespace std; #define rep(i,n,m) for(int i=(n);i<=(m);++i) #define re1(i,n) rep(i,1,n) #define re0(i,n) rep(i,0,n) const int maxnum=100+1; const int maxint=2147483647; char a[maxnum]; int dp[maxnum][maxnum]; char add[maxnum][maxnum]; int work(int i,int j){ int &ans=dp[i][j]; if(ans!=-1) return ans; if(i>j) return ans=0; if(i==j) return ans=1; ans=maxint; if(a[i]=='(' && a[j]==')' || a[i]=='[' && a[j]==']'){ add[i][j]=-1; ans = work(i+1,j-1); } rep(k,i,j-1){ int t = work(i,k)+work(k+1,j); if(t<ans){ ans=t; add[i][j]=k; } } return ans; } void make(int i,int j){ if(i>j) return; if(i==j){ if(a[i]=='(' || a[i]==')') printf("()"); else printf("[]"); }else{ if(add[i][j]==-1){ printf("%c",a[i]); make(i+1,j-1); printf("%c",a[j]); }else{ make(i,add[i][j]); make(add[i][j]+1,j); } } } int main(){ while(~scanf("%s",a)){ int la=strlen(a); re0(u,la-1)re0(w,la-1){ dp[u][w]=-1; add[u][w]=-2; } work(0,la-1); make(0,la-1); puts(""); } }