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
#include <bits/stdc++.h>
#define fi first
#define sc second
#define forn(i,p,k) for(int i=(p);i<=(k);++i)
#define forr(i,k,p) for(int i=(k);i>=(p);--i)
#define ALL(v)  begin(v), end(v)
#define RET(smth)   return void(cout<<smth<<'\n');
#define SIZ(v) (int)v.size()
using namespace std;
using pii = pair<int,int>;
using ll = long long;
#ifdef DEBUG
#include "debug.h"
#else
#define debug(...) ;
#endif

vector<long long> dp[2];
vector<vector<long long>> cost;
void solve(int p, int k, int l, int r) {
    if(p > k)   return;
    if(l == r) {
        for(int i=p;i<=k;i++)   dp[1][i] = dp[0][l] + cost[l+1][i];
        return;
    }
    int m = (p+k)/2;
    int opt = l;
    dp[1][m] = 1e18;
    for(int i=l;i<m&&i<=r;i++) {
        auto tmp = dp[0][i] + cost[i+1][m];
        if(tmp < dp[1][m]) {
            opt = i;
            dp[1][m] = tmp;
        }
    }
    solve(p,m-1,l,opt);
    solve(m+1,k,opt,r);
}

int main() {
#ifndef DEBUG
    ios_base::sync_with_stdio(0); cin.tie(0);
#endif
    int n,k;
    string S;
    cin >> n >> k >> S;
    cost = vector<vector<long long>>(n+1, vector<long long>(n+1,0));
    dp[0] = vector<long long>(n+1);
    dp[1] = vector<long long>(n+1);
    stack<pair<int,bool>> sta;
    auto calc_cost = [&](int ind) {
        long long res = 0;
        for(int i=ind-1;i<n;i++) {
            if(S[i] == '(') {
                if(sta.empty() || sta.top().second) {
                    sta.push({0, true});
                } else {
                    sta.top().second = true;
                }
            } else {
                if(!sta.empty()) {
                    if(sta.top().second) {
                        sta.top().second = false;
                        res += ++sta.top().first;
                    } else {
                        sta.pop();
                        if(!sta.empty()) {
                            sta.top().second = false;
                            res += ++sta.top().first;
                        }
                    }
                }
            }
            cost[ind][i+1] = res;
        }
        while(!sta.empty()) sta.pop();
    };
    for(int i=1;i<=n;i++)   calc_cost(i);
    for(int i=1;i<=n;i++)   dp[0][i] = cost[1][i];
    for(int i=2;i<=k;i++) {
        solve(1,n,1,n);
        swap(dp[0],dp[1]);
    }
    cout << dp[0][n] << '\n';
    return 0;
}