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
#include <bits/stdc++.h>
#define dbg(x) " [" << #x << ": " << (x) << "] "
using namespace std;
template<typename A, typename B>
ostream& operator<<(ostream& out, const pair<A,B>& p) {
    return out << "(" << p.first << ", " << p.second << ")";
}
template<typename T>
ostream& operator<<(ostream& out, const vector<T>& c) {
    out << "{";
    for(auto it = c.begin(); it != c.end(); it++) {
        if(it != c.begin()) out << ", ";
        out << *it;
    }
    return out << "}";
}
vector<vector<long long>> dp, cst;
void rec(int k, int i, int j, int l, int r) {
    if(i > j) return;
    int m = (i + j) >> 1;
    int opt = i;
    for(int x = l; x <= min(r, m); x++) {
        if(dp[k - 1][x - 1] + cst[x][m] < dp[k][m]) {
            dp[k][m] = dp[k - 1][x - 1] + cst[x][m];
            opt = x;
        }
    }
    rec(k, i, m - 1, l, opt);
    rec(k, m + 1, j, opt, r);
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int n,k;
    cin >> n >> k;
    string s;
    cin >> s;
    s = "#" + s;
    vector<vector<long long>> v(n + 1, vector<long long>(n + 1));
    cst.assign(n + 1, vector<long long>(n + 1));
    vector<int> sm(n + 1);
    for(int i = 1; i < n + 1; i++) {
        sm[i] = sm[i - 1] + (s[i] == '(' ? 1 : -1);
    }
    for(int i = 1; i < n + 1; i++) {
        for(int j = i; j < n + 1; j++) {
            if(sm[j] < sm[i - 1]) break;
            if(sm[j] == sm[i - 1]) v[i][j]++;
        }
    }
    for(int i = n; i >= 1; i--) {
        for(int j = i + 1; j < n + 1; j++) {
            v[i][j] += v[i + 1][j];
        }
    }
    for(int i = 1; i < n + 1; i++) {
        for(int j = i; j < n + 1; j++) {
            cst[i][j] = cst[i][j - 1] + v[i][j];
        }
    }
    dp.assign(k + 1, vector<long long>(n + 1, 1e9));
    dp[0][0] = 0;
    for(int i = 1; i < k + 1; i++) {
        rec(i, 1, n, 1, n);
    }
    cout << dp[k][n] << endl;
    return 0;
}