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
#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
using namespace std;

int pref[5009], popr[5009][5009], dp[5009][5009];
string s;

int main()
{
	ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	int n, k, a = 0, b;
	cin>>n>>k>>s;
	for(int i=0; i<s.size(); i++)
	{
		if(s[i] == '(') a++;
		else a--;
		pref[i+1] = a;
	}
	for(int i=1; i<=n; i++)
	{
		a = b = 0;
		if(pref[i-1] < pref[i]) b = 1;
		for(int j=i-1; j>=1; j--)
		{
			if(pref[j-1] < pref[i]) b = 1;
			if(pref[j-1] == pref[i] && b == 0) a++;
			popr[j][i] = popr[j][i-1] + a;
		}
	}
	
	for(int i=1; i<=n; i++)
	{
		for(int j=1; j<=i; j++)
		{
			if(j > k) break;
			if(j == 1)
			{
				dp[i][j] = popr[1][i];
				continue;
			}
			a = 1e9;
			for(int l=j-1; l<=i-1; l++) a = min(a, dp[l][j-1] + popr[l+1][i]);
			dp[i][j] = a;
		}
	}
	cout<<dp[n][k];
	return 0;
}