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
#include<bits/stdc++.h>
using namespace std;
using lld = long long;

const lld INF = 1e18;

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

	int n,k;
	cin >> n >> k;

	string s;
	cin >> s;

	vector<vector<lld>> dp(k+1, vector<lld>(n+1, INF));
	vector<int> cnt(2*n, 0);

	{
		int b = 0;
		lld val = 0;
		for(int i=0;i<n;i++) {
			if(s[i] == '(') {
				cnt[b+n]++;
				b++;
			} else {
				cnt[b+n] = 0;
				b--;
				val += cnt[b+n];
			}

			dp[1][i+1] = val;
		}
	}

	for(int j=2;j<=k;j++)
		for(int l=j-1;l<=n;l++) {
			fill(cnt.begin(), cnt.end(), 0);
			int b = 0;
			lld val = 0;
			for(int i=l;i<n;i++) {
				if(s[i] == '(') {
					cnt[b+n]++;
					b++;
				} else {
					cnt[b+n] = 0;
					b--;
					val += cnt[b+n];
				}

				dp[j][i+1] = min(dp[j][i+1], val + dp[j-1][l]);
			}
		}

	cout << dp[k][n] << "\n";

	return 0;
}