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 <iostream>
#include <stack>

const int64_t INF = 1ull<<62;

int n,k;
std::string N;

struct E{
    int l;
    int c;
};

int64_t D[4001][4001];
int64_t F[4001][4001];


void score(int a) {
    int64_t sum  = 0;
    std::stack<E> S;
    int l = 0;
    for (int i=a;i<n;++i) {
        char c = N[i];
        if (c == '(') {
            if (S.empty() || S.top().l < l) S.push({l, 0});
            ++l;
        } else {
            --l;
            while (!S.empty() && S.top().l > l) {
                S.pop();
            }
            if (!S.empty() && S.top().l == l) {
                S.top().c++;
                sum += S.top().c;
            }
        }
        D[a][i] = sum;
    }
}


int main() {
    std::ios_base::sync_with_stdio(0);
    std::cin >> n >> k;
    std::cin >> N;
    for (int i=0;i<n;++i) score(i);

    // std::clog << " :: " << n << " " << k << std::endl;


    // for (int i=0;i<n;++i)
    // {
    //     std::clog << i << " :: ";
    //     for (int j=0;j<n;++j)
    //         std::clog << D[i][j] << " ";
    //     std::clog << std::endl;
    // }

    for (int i=0;i<=k;++i)
        for (int j=0;j<n;++j)
            F[i][j] = INF;
    for (int i=0;i<n;++i)
        F[0][i] = D[0][i];
    for (int i=1;i<k;++i) {
        for (int j=i;j<n;++j) {
            F[i][j] = INF;
            for (int l=0;l<=j;++l) {
                F[i][j] = std::min(F[i][j], F[i-1][l] + D[l+1][j]);
                // std::clog << i << " " << j << " ( " << l << " ) " << " = " << F[i][j] << " vs " << F[i-1][l] + D[l+1][j] << std::endl;
                // std::clog << " :: " <<  D[0][l] << "(" << F[0][l] << ")" << " + " << D[l+1][j]  << " = " << D[0][l]+ D[l+1][j] << std::endl;
            }
        }
    }
    std::cout << F[k-1][n-1] << std::endl;
    return 0;
}