携程HDU第一场1002 - 括号匹配
比赛水了,这是第二题括号匹配水题。经典问题。
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 5 int N; 6 int dp[100][100]; 7 char s[101]; 8 9 #define min(a,b) ((a)>(b)?(b):(a)) 10 11 12 int main(void) 13 { 14 int l; 15 for(cin >> N; N; --N) { 16 cin >> s; l = strlen(s); 17 int i, j, k; 18 for(j=0; j<l; ++j) dp[j][0] = 1; 19 for(j=0; j<l; ++j) { 20 dp[j][1] = 0x3f3f3f3f; 21 if ((s[j] == '(' && s[j+1] == ')') || (s[j] == '[' && s[j+1] == ']')) 22 dp[j][1] = 0; 23 else { 24 if (s[j] == '(' || s[j] == '[') 25 dp[j][1] = min(dp[j+1][0] + 1, dp[j][1]); 26 if (s[j+1] == ')' || s[j+1] == ']') 27 dp[j][1] = min(dp[j][0] + 1, dp[j][1]); 28 } 29 dp[j][1] = min(dp[j][0] + dp[j+1][0], dp[j][1]); 30 } 31 for(i=2; i<l; ++i) { 32 for(j=0; j<l; ++j) { 33 dp[j][i] = 0x3f3f3f3f; 34 if ((s[j] == '(' && s[j+i] == ')') || (s[j] == '[' && s[j+i] == ']')) 35 dp[j][i] = min(dp[j+1][i-2], dp[j][i]); 36 else { 37 if (s[j] == '(' || s[j] == '[') 38 dp[j][i] = min(dp[j+1][i-1] + 1, dp[j][i]); 39 if (s[j+i] == ')' || s[j+i] == ']') 40 dp[j][i] = min(dp[j][i-1] + 1, dp[j][i]); 41 } 42 for(k=0; k<i; ++k) 43 dp[j][i] = min(dp[j][k] + dp[j+k+1][i-k-1], dp[j][i]); 44 } 45 } 46 cout << dp[0][l-1] << endl; 47 } 48 return 0; 49 }
This article is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
本文采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。