紫书278页的题目,纪念一下坑比的输入格式,实在是无语了;
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> using namespace std; const int maxn = 100 + 5; char S[maxn]; int n, d[maxn][maxn]; bool match(char a, char b) { return (a == '(' && b == ')') || (a == '[' && b == ']'); } void dp() { for(int i = 0; i < n; i++) { d[i+1][i] = 0; d[i][i] = 1; } for(int k=2; k<=n; k++) { for(int i=0; i<=n-k; i++) { int j = i+k-1; d[i][j] = n; if(match(S[i], S[j])) d[i][j] = min(d[i][j], d[i+1][j-1]); for(int w=i; w<=j-1; w++) d[i][j] = min(d[i][j], d[i][w] + d[w+1][j]); } } } void print(int i, int j) { if(i > j) return ; if(i == j) { if(S[i] == '(' || S[i] == ')') printf("()"); else printf("[]"); return; } int ans = d[i][j]; if(match(S[i], S[j]) && ans == d[i+1][j-1]) { printf("%c", S[i]); print(i+1, j-1); printf("%c", S[j]); return; } for(int k = i; k < j; k++) if(ans == d[i][k] + d[k+1][j]) { print(i, k); print(k+1, j); return; } } int main() { int T; scanf("%d", &T); getchar(); while(T--) { //gets(S); getchar(); gets(S); n = strlen(S) ;//- 1; //cout << n << endl; memset(d, -1, sizeof(d)); dp(); print(0, n-1); printf("\n"); if(T) printf("\n"); } return 0; }
水波....