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;

typedef long long ll;

const int N = 4e2+1;
const ll INF = 1e18;

ll c[N][N], dp[N][N], x[N];
string s;
int lf[N];

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    cout.tie(NULL);
    
    int n, k; cin>>n>>k;
    cin>>s;
    s="0"+s;

    stack<int> st;
    for (int i=1; i<=n; ++i) {
        if (s[i] == '(') lf[i]=-1, st.push(i);
        else {
            if (st.empty()) lf[i]=-1;
            else lf[i]=st.top(), st.pop();
        }
    }

    for (int i=1; i<=n; ++i) {
        memset(x, 0, sizeof(x));
        c[i][i]=0;

        for (int j=i+1; j<=n; ++j) {
            c[i][j]=c[i][j-1];
            if (lf[j] < i) continue;
            x[j]=x[lf[j]-1]+1;
            c[i][j]+=x[j];
        }
    }

    for (int i=0; i<=n; ++i) {
        for (int j=0; j<=k; ++j) dp[i][j]=INF;
        dp[0][i]=0;
    }

    ll ans=c[1][n];
    for (int i=1; i<n; ++i) {
        for (int x=1; x<k; ++x) {
            for (int j=0; j<i; ++j) dp[i][x]=min(dp[i][x], dp[j][x-1]+c[j+1][i]);
            ans=min(ans, dp[i][x]+c[i+1][n]);
        }
    }

    cout<<ans<<"\n";
}