#include <iostream> #include <climits> using namespace std; const int MAX_N = 307; int n, K; int a[MAX_N]; int pass[MAX_N][MAX_N]; int dp[MAX_N][MAX_N]; void init() { cin >> n >> K; for (int i = 1; i <= n; i++) { char c; cin >> c; if (c == '(') a[i] = 1; else a[i] = -1; } } void preprocess() { for (int i = 1; i <= n; i++) { if (a[i] == -1) { continue; } int pref = 1; for (int j = i + 1; j <= n; j++) { pref += a[j]; if (pref < 0) { break; } if (pref == 0) { for (int l = 1; l <= i; l++) { for (int r = j; r <= n; r++) { pass[l][r]++; } } } } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); init(); preprocess(); for (int k = 1; k <= K; k++) { for (int i = 1; i <= n; i++) { dp[k][i] = MAX_N * MAX_N; } } for (int i = 1; i <= n; i++) { dp[1][i] = pass[1][i]; } for (int k = 2; k <= K; k++) { for (int i = 1; i <= n; i++) { int mini = MAX_N * MAX_N; for (int j = 1; j < i; j++) { mini = min(dp[k - 1][j] + pass[j + 1][i], mini); } dp[k][i] = mini; } } /* cout << "PASS:\n"; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cout << pass[i][j] << ' '; } cout << '\n'; } cout << '\n'; cout << "DP:\n"; for (int k = 0; k < K; k++) { for (int i = 0; i <= n; i++) { cout << dp[k][i] << ' '; } cout << '\n'; } */ cout << dp[K][n] << '\n'; return 0; }
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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | #include <iostream> #include <climits> using namespace std; const int MAX_N = 307; int n, K; int a[MAX_N]; int pass[MAX_N][MAX_N]; int dp[MAX_N][MAX_N]; void init() { cin >> n >> K; for (int i = 1; i <= n; i++) { char c; cin >> c; if (c == '(') a[i] = 1; else a[i] = -1; } } void preprocess() { for (int i = 1; i <= n; i++) { if (a[i] == -1) { continue; } int pref = 1; for (int j = i + 1; j <= n; j++) { pref += a[j]; if (pref < 0) { break; } if (pref == 0) { for (int l = 1; l <= i; l++) { for (int r = j; r <= n; r++) { pass[l][r]++; } } } } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); init(); preprocess(); for (int k = 1; k <= K; k++) { for (int i = 1; i <= n; i++) { dp[k][i] = MAX_N * MAX_N; } } for (int i = 1; i <= n; i++) { dp[1][i] = pass[1][i]; } for (int k = 2; k <= K; k++) { for (int i = 1; i <= n; i++) { int mini = MAX_N * MAX_N; for (int j = 1; j < i; j++) { mini = min(dp[k - 1][j] + pass[j + 1][i], mini); } dp[k][i] = mini; } } /* cout << "PASS:\n"; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cout << pass[i][j] << ' '; } cout << '\n'; } cout << '\n'; cout << "DP:\n"; for (int k = 0; k < K; k++) { for (int i = 0; i <= n; i++) { cout << dp[k][i] << ' '; } cout << '\n'; } */ cout << dp[K][n] << '\n'; return 0; } |