标签:
题解:
区间dp,打印解时递归打印
代码:
#include<bits/stdc++.h> using namespace std; #define pb push_back #define mp make_pair #define se second #define fs first #define ll long long #define CLR(x) memset(x,0,sizeof x) #define MC(x,y) memcpy(x,y,sizeof(x)) #define SZ(x) ((int)(x).size()) #define FOR(it,c) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();it++) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define INF 1e9 typedef pair<int,int> P; const double eps=1e-9; const int maxnnode=11000; const int maxn=150+10; const int mod=20071027; int dp[105][105],div_dp[105][105]; char line[110]; void print(int i,int j) { if(i>j) return; if(i==j) { if(line[i]==‘(‘||line[i]==‘)‘) printf("()"); else printf("[]"); return; } if(div_dp[i][j]==-1) { putchar(line[i]); print(i+1,j-1); putchar(line[j]); return ; } print(i,div_dp[i][j]); print(div_dp[i][j]+1,j); } int main() { int n; scanf("%d",&n); getchar(); while(n--){ gets(line); gets(line); CLR(div_dp); int len=strlen(line); for(int i=0;i<len;i++) { dp[i+1][i]=0; dp[i][i]=1; } for(int l=1;l<len;l++) { for(int i=0;i<len-l;i++) { int j=i+l; dp[i][j]=INF; if((line[i]==‘(‘&&line[j]==‘)‘)||(line[i]==‘[‘&&line[j]==‘]‘)) { dp[i][j]=dp[i+1][j-1]; div_dp[i][j]=-1; } for(int k=i;k<j;k++) { if(dp[i][k]+dp[k+1][j]<dp[i][j]) { dp[i][j]=dp[i][k]+dp[k+1][j]; div_dp[i][j]=k; } } } } print(0,len-1); printf("\n"); if(n) printf("\n"); } }
标签:
原文地址:http://www.cnblogs.com/byene/p/5802306.html