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
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef unsigned int ui;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<long long> vll;
const ll LINF = 1e18;
const int INF = 1e9;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, k;
    cin >> n >> k;

    string word;
    cin >> word;

    int cnt_dyck_words[n][n];
    memset(cnt_dyck_words, 0, sizeof(cnt_dyck_words));

    for (int i = 0; i < n; ++i) {
        int open_parenthesis = 0;
        for (int j = i; j < n; ++j) {
            if (word[j] == '(') {
                ++open_parenthesis;
            } else {
                --open_parenthesis;
            }
            if (open_parenthesis < 0) {
                break;
            }
            cnt_dyck_words[i][j] = open_parenthesis == 0;
        }
    }

    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            cnt_dyck_words[i][j] += cnt_dyck_words[i][j - 1];
        }
    }

    for (int i = n - 2; i >= 0; --i) {
        for (int j = i + 1; j < n; ++j) {
            cnt_dyck_words[i][j] += cnt_dyck_words[i + 1][j];
        }
    }

    // for (int i = 0; i < n; ++i) {
    //     for (int j = 0; j < n; ++j) {
    //         cerr << cnt_dyck_words[i][j] << ' ';
    //     }
    //     cerr << '\n';
    // }

    int subarray_sum[n][k];
    memset(subarray_sum, 0, sizeof(subarray_sum));

    for (int i = 0; i < n; ++i) {
        subarray_sum[i][0] = cnt_dyck_words[0][i];
        for (int j = 1; j < k; ++j) {
            int mn = INF;
            for (int split = 0; split < i; ++split) {
                mn = min(mn, subarray_sum[split][j - 1] + cnt_dyck_words[split + 1][i]);
            }
            subarray_sum[i][j] = mn;
        }
    }

    cout << subarray_sum[n - 1][k - 1] << endl;

    return 0;
}