UVA - 1626 Brackets sequence DP
2017-08-15 10:03
316 查看
题目传送门:https://vjudge.net/problem/UVA-1626
lrj 紫书 278页
这个题可以看作:用DP求最少添加的括号数
那么这个题就比较短了,只有solve() 函数中的那一部分
dp [ i ] [ j ] 之间的转移就够了,,
本题另一部分就是打印解: 打印时会遇到4种情况,就是print()函数中3个if()和最后的 for循环,,分别理解下其正确性就好了
lrj 紫书 278页
这个题可以看作:用DP求最少添加的括号数
那么这个题就比较短了,只有solve() 函数中的那一部分
dp [ i ] [ j ] 之间的转移就够了,,
本题另一部分就是打印解: 打印时会遇到4种情况,就是print()函数中3个if()和最后的 for循环,,分别理解下其正确性就好了
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <set> #include <stack> #include <queue> #include <ctype.h> #include <vector> #include <algorithm> // cout << " === " << endl; using namespace std; typedef long long ll; const int maxn = 100 + 7, INF = 0x3f3f3f3f, mod = 1e9+7; int T, n, dp[maxn][maxn]; char s[maxn]; bool match(char a, char b) { if((a == '(' && b == ')') || (a == '[' && b == ']') ) return true; return false; } void print(int l, int r) { if(l > r) return; if(l == r) { if(s[l] == '(' || s[l] == ')') printf("()"); else if(s[l] == '[' || s[l] == ']') printf("[]"); return; } int ans = dp[l][r]; if(match(s[l], s[r]) && ans == dp[l+1][r-1]) { printf("%c",s[l]); print(l+1, r-1); printf("%c",s[r]); return; } for(int k = l; k < r; ++k) { if(ans == (dp[l][k] + dp[k+1][r])) { print(l, k); print(k+1, r); return; } } } void solve() { for(int i = 0; i < n; ++i) { dp[i+1][i] = 0; dp[i][i] = 1; } for(int i = n-2; i >= 0; --i) { for(int j = i+1; j < n; ++j) { dp[i][j] = INF; if(match(s[i], s[j])) dp[i][j] = min(dp[i][j], dp[i+1][j-1]); for(int k = i; k < j; ++k) dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j]); } } } int main() { scanf("%d", &T); getchar(); while(T--) { gets(s); gets(s); n = strlen(s); if(n) solve(); if(n) print(0, n-1); puts(""); if(T) puts(""); } return 0; }
相关文章推荐
- Brackets sequence UVA - 1626 (典型的区间dp+递归打印路径)
- UVA 1626 Brackets sequence——dp
- Brackets sequence UVA - 1626(区间dp)
- Brackets sequence UVA - 1626
- UVa 10534 - Wavio Sequence DP+最长上升子序列(严格上升)+二分查找(nlogn)
- UVA 10534 Wavio Sequence DP(LIS+二分)
- Brackets sequence UVA - 1626 区间dp
- DP Brackets Sequence POJ 1141
- UVA 1626 区间DP
- UVa 1626:Brackets Sequence(DP)
- [UVALive3675]Sorted bit sequence && 数位DP
- uva 348 Optimal Array Multiplication Sequence(区间dp)
- poj 1141 Brackets Sequence(区间dp)
- UVA 1626 - Brackets sequence 区间DP
- UVA 1626 Brackets sequence 区间DP
- UVa 348 Optimal Array Multiplication Sequence (DP 最优矩阵链乘)
- UVA 348 Optimal Array Multiplication Sequence(区间dp)
- UVA1626 DP经典
- poj 1141 Brackets Sequence dp
- Optimal Array Multiplication Sequence+uva+简单区间dp