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
/*
    Zadanie: Nawiasowe podziały
    Autor: Tomasz Kwiatkowski
*/

#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back

using namespace std;
typedef long long ll;

const int MAXN = 4e3 + 7;
const int INF = 1e9 + 7;

ll cnt[MAXN][MAXN];
ll dp[MAXN][MAXN];

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

    int N, K;
    cin >> N >> K;
    string s;
    cin >> s;
    for (int i = 1; i <= N; ++i) {
        int d = 0;
        for (int j = i; j <= N; ++j) {
            d += (s[j - 1] == '(' ? 1 : -1);
            if (d < 0) break;
            if (d == 0) {
                ++cnt[1][j];
                --cnt[i + 1][j];
            }
        }
    }
    for (int j = 1; j <= N; ++j) {
        for (int i = 1; i <= N; ++i)
            cnt[i][j] += cnt[i - 1][j];
    }
    for (int i = 1; i <= N; ++i) {
        for (int j = 1; j <= N; ++j)
            cnt[i][j] += cnt[i][j - 1];
    }

    for (int i = 1; i <= N; ++i) {
        dp[i][0] = cnt[1][i];
        for (int k = 1; k < K; ++k) {
            dp[i][k] = 1e18;
            for (int j = 0; j < i; ++j)
                dp[i][k] = min(dp[i][k], dp[j][k - 1] + cnt[j + 1][i]);
        }
    }
    cout << dp[N][K - 1] << '\n';
    return 0;
}