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

using namespace std;

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

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

	string B;
	cin >> B;

	vector<pair<int, int>> V;
	vector<vector<int>> E(n);
	stack<pair<bool, int>> S;
	for (int i = 0; i < n; i++) {
		bool is_open = (B[i] == '(');
		if (S.size() && S.top().first == !is_open) {
			int prev = S.top().second;
			V.push_back({ prev, i });
			E[i].push_back(prev);
			S.pop();
			if (prev > 0) {
				for (auto& e : E[prev - 1]) {
					V.push_back({ e, i });
					E[i].push_back(e);
				}
			}
		}
		else if (is_open)
			S.push({ is_open, i });
	}

	vector<vector<int>> I(n + 1, vector<int>(n + 1));
	vector<int> TD(n + 1);
	for (auto& [a, b] : V) {
		for (int i = a + 1; i <= b; i++) {
			I[i][a]++, TD[i]++;
		}
	}

	vector<vector<int>> DP(n + 1, vector<int>(k));
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j < k; j++) {
			int overlap = 0;
			for (int z = 0; z < i; z++) {
				overlap += I[i][z];
				DP[i][j] = max(DP[i][j], DP[z][j - 1] - overlap);
			}
			DP[i][j] += TD[i];
		}
	}

	int res = 0;
	for (int i = 0; i <= n; i++) 
		res = max(res, DP[i].back());
	cout << V.size() - res;
}