标签:
[[(([]
4
黑书上的原题。F(i, j)表示[i, j]符合要求添加括号最小数目。方程:
F(i, j) = 0, i>j;
F(i, j) = 1, i=j;
F(i, j) = min{ F(i+1, j-1) (ispair(i, j)), F(i+1, j) (s[i]=‘(‘||‘[‘), F(i, j-1) (s[i]=‘)‘||‘]‘), min{F(i, k) + F(k+1, j)} (i≤k≤j-1) };
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 int F[256][256]; 5 string s; 6 bool ispair(int i, int j) 7 { 8 return (s[i] == ‘(‘ && s[j] == ‘)‘) || (s[i] == ‘[‘ && s[j] == ‘]‘); 9 } 10 void mysearch(int l, int r) 11 { 12 if (F[l][r] != 200000000) 13 return; 14 else if (l > r) 15 F[l][r] = 0; 16 else if (l == r) 17 F[l][r] = 1; 18 else { 19 if (ispair(l, r)) { 20 mysearch(l + 1, r - 1); 21 if (F[l + 1][r - 1] < F[l][r]) 22 F[l][r] = F[l + 1][r - 1]; 23 } 24 if (s[l] == ‘(‘ || s[l] == ‘[‘) { 25 mysearch(l + 1, r); 26 if (F[l + 1][r] + 1 < F[l][r]) 27 F[l][r] = F[l + 1][r] + 1; 28 } 29 if (s[l] == ‘)‘ || s[l] == ‘]‘) { 30 mysearch(l, r - 1); 31 if (F[l][r - 1] + 1 < F[l][r]) 32 F[l][r] = F[l][r - 1] + 1; 33 } 34 for (int k = l; k <= r - 1; ++k) { 35 mysearch(l, k); 36 mysearch(k + 1, r); 37 if (F[l][k] + F[k + 1][r] < F[l][r]) 38 F[l][r] = F[l][k] + F[k + 1][r]; 39 } 40 } 41 } 42 int main() 43 { 44 cin >> s; 45 for (int i = 0; i != 256; ++i) 46 for (int j = 0; j != 256; ++j) 47 F[i][j] = 200000000; 48 mysearch(0, s.size() - 1); 49 cout << F[0][s.size() - 1]; 50 return 0; 51 }
标签:
原文地址:http://www.cnblogs.com/smileandyxu/p/5348519.html