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
// Author: Kajetan Ramsza
#include "bits/stdc++.h"

using namespace std;

template<typename F, typename S> ostream& operator<<(ostream& os, const pair<F, S> &p) { return os<<"("<<p.first<<", "<<p.second<<")"; }
template<typename T> ostream &operator<<(ostream & os, const vector<T> &v) { os << "{"; typename vector< T > :: const_iterator it;
    for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "}"; }

void dbg_out() { cerr<<'\n'; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr<<' '<<H; dbg_out(T...); }

#ifdef DEBUG
#define dbg(...) cerr<<"(" << #__VA_ARGS__ <<"):", dbg_out(__VA_ARGS__)
#else
#define dbg(...) 
#endif

typedef long long ll;

const ll inf = ll(1e18) + 7;

int n, k;
string s;

vector<int> sum;

vector<vector<ll>> dp;
vector<vector<ll>> naw;

ll calc(int a, int b) {
    dbg(a, b);
    ll res = 0;
    for(int i=a;i<b;i++) {
        if(s[i] != '(') continue;
        for(int j=i+1;j<=b;j++) {
            if(sum[j] < sum[i-1]) break;
            if(s[j] != ')') continue;
            if(sum[i-1] != sum[j]) continue;
            res++;
        }
    }
    dbg(res);
    return res;
}

void preprocess() {
    for(int i=1;i<=n;i++) {
        for(int j=i;j<=n;j++) {
            naw[i][j] = calc(i, j);
        }
    }
}

void solve(int j, int l, int r, int a, int b) {
    dbg(j, l, r, a, b);
    if(l > r) return;
    int mid = (l + r) / 2;
    dbg(mid);
    int ind = -1;
    for(int i=a;i<=min(mid-1, b);i++) {
        ll val = dp[i][j-1] + naw[i+1][mid];
        dbg(i, val);
        if(val < dp[mid][j]) {
            dp[mid][j] = val;
            ind = i;
        }
    }
    dbg(dp[mid][j], ind);
    assert(ind != -1);
    solve(j, l, mid-1, a, ind);
    solve(j, mid+1, r, ind, b);
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin>>n>>k;
    cin>>s;
    s = "$" + s;

    sum.assign(n+1, 0);
    for(int i=1;i<=n;i++) {
        sum[i] = sum[i-1];
        if(s[i] == '(') sum[i]++;
        else sum[i]--;
    }
    dbg(sum);

    naw.assign(n+1, vector<ll>(n+1,inf));
    preprocess();
    dp.assign(n+1, vector<ll>(k+1,inf));
    dp[0][0] = 0;
    for(int j=1;j<=k;j++) {
        solve(j, j, n, j-1, n);
    }
    cout<<dp[n][k]<<'\n';
}