#include <bits/stdc++.h> using namespace std; const size_t INF = numeric_limits<size_t>::max(); struct TestCase { size_t n, k; string s; }; TestCase read_test_case(); void solve_test_case(const TestCase&); int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve_test_case(read_test_case()); } TestCase read_test_case() { TestCase tc; cin >> tc.n >> tc.k >> tc.s; return tc; } void solve_test_case(const TestCase& tc) { vector<vector<size_t>> dp(tc.n + 1, vector<size_t>(tc.k + 1, INF)); dp[tc.n][0] = 0; for (int begin = tc.n - 1; begin >= 0; begin--) { size_t score = 0; stack<size_t> s; for (size_t j = begin; j < tc.n; j++) { if (tc.s[j] == '(') s.push(0); else if (tc.s[j] == ')' && !s.empty()) { // pop content of closed paren while (!s.empty() && s.top() > 0) s.pop(); // found closing brace if (!s.empty()) { s.pop(); // Pop ( // Add 1 to current sequence of parens if (!s.empty() && s.top() > 0) s.top()++; else s.push(1); } if (!s.empty()) score += s.top(); } for (size_t k = 1; k <= tc.k; k++) if (dp[j + 1][k - 1] != INF) dp[begin][k] = min(dp[begin][k], dp[j + 1][k - 1] + score); } } cout << dp[0][tc.k] << "\n"; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | #include <bits/stdc++.h> using namespace std; const size_t INF = numeric_limits<size_t>::max(); struct TestCase { size_t n, k; string s; }; TestCase read_test_case(); void solve_test_case(const TestCase&); int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve_test_case(read_test_case()); } TestCase read_test_case() { TestCase tc; cin >> tc.n >> tc.k >> tc.s; return tc; } void solve_test_case(const TestCase& tc) { vector<vector<size_t>> dp(tc.n + 1, vector<size_t>(tc.k + 1, INF)); dp[tc.n][0] = 0; for (int begin = tc.n - 1; begin >= 0; begin--) { size_t score = 0; stack<size_t> s; for (size_t j = begin; j < tc.n; j++) { if (tc.s[j] == '(') s.push(0); else if (tc.s[j] == ')' && !s.empty()) { // pop content of closed paren while (!s.empty() && s.top() > 0) s.pop(); // found closing brace if (!s.empty()) { s.pop(); // Pop ( // Add 1 to current sequence of parens if (!s.empty() && s.top() > 0) s.top()++; else s.push(1); } if (!s.empty()) score += s.top(); } for (size_t k = 1; k <= tc.k; k++) if (dp[j + 1][k - 1] != INF) dp[begin][k] = min(dp[begin][k], dp[j + 1][k - 1] + score); } } cout << dp[0][tc.k] << "\n"; } |