POJ_1141_Brackets Sequence
来源:互联网 发布:程序员笔记本推荐 知乎 编辑:程序博客网 时间:2024/06/05 14:32
#include <iostream>#include <cstring>#include <climits>using namespace std;#define SIZE 105char s[SIZE];int len;int DP[SIZE][SIZE];int pos[SIZE][SIZE];void DP(){ for( int i = 0; i < len; ++i ) DP[i][i] = 1; for( int k = 1; k < len; ++k ){ for( int i = 0; i < len - k; ++i ){ int j = i + k; char left = s[i]; char right = s[j]; DP[i][j] = 1e9; if( ( left == '(' && right == ')' ) || ( left == '[' && right == ']' ) ){ DP[i][j] = min( DP[i][j] , DP[i + 1][j - 1] ); pos[i][j] = -1; } for( int p = i; p < j; ++p ){ if( DP[i][j] > DP[i][p] + DP[p + 1][j] ){ pos[i][j] = p; DP[i][j] = DP[i][p] + DP[p + 1][j]; } } } }}void show( int i, int j ){ if( j < i ) return ; if( j == i ){ if( s[i] == '(' || s[i] == ')' ) cout << "()"; else cout << "[]"; } else{ if( pos[i][j] == -1 ){ cout << s[i]; show( i + 1, j - 1 ); cout << s[j]; } else{ show( i, pos[i][j] ); show( pos[i][j] + 1, j ); } }}int main(){ cin >> s; len = strlen( s ); DP(); show( 0, len - 1 ); cout << endl; return 0;}