#include <bits/stdc++.h> using namespace std; int n, k; long long mw(int s, vector<vector<long long>> &dp, int d, vector<vector<long long>> &chs) { if (chs[s][d] != -1) return chs[s][d]; if (s >= n) return 1e18; if (d == k) return dp[s][n - 1]; long long lmao = 1e18; for (int i = s; i < n; i++) lmao = min(lmao, dp[s][i] + mw(i + 1, dp, d + 1, chs)); chs[s][d] = lmao; return lmao; } int main() { ios_base::sync_with_stdio(0); string s; cin >> n >> k >> s; vector<vector<bool>> w(n, vector<bool>(n)); vector<vector<long long>> dp(n, vector<long long>(n)); vector<vector<long long>> csh(n + 1, vector<long long>(n + 1, -1)); for (int i = 0; i < n; i++) { int c = 0; for (int j = i; j < n; j++) { if (s[j] == ')') c--; else c++; if (c < 0) break; if (c == 0) w[i][j] = 1; } } for (int l = 1; l <= n; l++) { for (int i = 0; i + l <= n; i++) { dp[i][i + l - 1] = w[i][i + l - 1]; if (l > 1) dp[i][i + l - 1] += dp[i + 1][i + l - 1] + dp[i][i + l - 2]; if (l > 2) dp[i][i + l - 1] -= dp[i + 1][i + l - 2]; // cout << i << ' ' << l << ' ' << dp[i][i + l - 1] << '\n'; } } // vector<vector<long long>> dp2(n, vector<long long>(n)); cout << mw(0, dp, 1, csh) << '\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 | #include <bits/stdc++.h> using namespace std; int n, k; long long mw(int s, vector<vector<long long>> &dp, int d, vector<vector<long long>> &chs) { if (chs[s][d] != -1) return chs[s][d]; if (s >= n) return 1e18; if (d == k) return dp[s][n - 1]; long long lmao = 1e18; for (int i = s; i < n; i++) lmao = min(lmao, dp[s][i] + mw(i + 1, dp, d + 1, chs)); chs[s][d] = lmao; return lmao; } int main() { ios_base::sync_with_stdio(0); string s; cin >> n >> k >> s; vector<vector<bool>> w(n, vector<bool>(n)); vector<vector<long long>> dp(n, vector<long long>(n)); vector<vector<long long>> csh(n + 1, vector<long long>(n + 1, -1)); for (int i = 0; i < n; i++) { int c = 0; for (int j = i; j < n; j++) { if (s[j] == ')') c--; else c++; if (c < 0) break; if (c == 0) w[i][j] = 1; } } for (int l = 1; l <= n; l++) { for (int i = 0; i + l <= n; i++) { dp[i][i + l - 1] = w[i][i + l - 1]; if (l > 1) dp[i][i + l - 1] += dp[i + 1][i + l - 1] + dp[i][i + l - 2]; if (l > 2) dp[i][i + l - 1] -= dp[i + 1][i + l - 2]; // cout << i << ' ' << l << ' ' << dp[i][i + l - 1] << '\n'; } } // vector<vector<long long>> dp2(n, vector<long long>(n)); cout << mw(0, dp, 1, csh) << '\n'; } |