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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
//Autor: Michał Szeliga
#ifdef LOCAL
#define debug(...) __VA_ARGS__;
#else
#define debug(...) {}
#endif
bool czydobry[1005][1005];
ll dp[1005][1005];
ll ile[1005][1005];
ll n,k;
ll suma[1005][1005];
ll wy[1005][1005];
const ll INF = 21372137213722;
void solve1(){
	ll i;
	for (i = 0; i < n+1; i++){
		for (ll j = 0; j < k+1; j++) wy[i][j] = INF;
	}
	wy[0][0] = 0;
	for (i = 1; i < n+1; i++){
		for (ll j = 1; j < i+1; j++){
			for (ll ilek = 1; ilek < k+1; ilek++){
			//	cout<<i<<" "<<j<<" # "<<ilek<<" ### "<<wy[j-1][ilek]<<" "<<dp[j][i]<<"\n";
				wy[i][ilek] = min(wy[i][ilek],wy[j-1][ilek-1]+dp[j][i]); 
				
			}
		}
	}
	/*for (i = 1; i < n+1; i++){
		cout<<"DLA i = "<<i<<": ";
		for (ll j = 0; j < k+1; j++) cout<<wy[i][j]<<" ";
		cout<<"\n";
	}*/
	cout<<wy[n][k]<<"\n";
}
void licz_dp(ll x, ll a, ll b, ll l, ll p){
    ll r = (a+b)/2;
    ll punkt = 0;
    wy[r][x] = dp[1][r];
    for (ll i = l; i <= r; i++){
        if (wy[r][x] > wy[i][x-1]+dp[i+1][r]){
            wy[r][x] = wy[i][x-1]+dp[i+1][r];
            punkt = i;
        }
    }   
    if (a < b){
        licz_dp(x,a,r-1,l,punkt);
        licz_dp(x,r+1,b,punkt,p);
    }
}
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    ll i;
	cin>>n>>k;
	string s;
	cin>>s;
	for (i = 1; i < n+1; i++){
		ll pre = 0;
		for (ll j = i; j < n+1; j++){
			if (s[j-1] == ')') pre--;
			else pre++;
			if (pre < 0) break;
			if (pre == 0) czydobry[i][j] = 1;
		}
	}
	for (i = n; i ; i--){
		for (ll j = i; j ; j--){
			suma[j][i] = suma[j+1][i]+czydobry[j][i];
		}
	}	
	for (i = 1; i < n+1; i++){
		for (ll j = i; j < n+1; j++){
			dp[i][j] = dp[i][j-1]+suma[i][j];
		}
	}
	if (n <= 400) solve1();
	else{
		for (i = 0; i < n+1; i++){
			for (ll j = 0; j < k+1; j++) wy[i][j] = INF;
		}
		wy[0][0] = 0;
		for (i = 1; i < k+1; i++) licz_dp(i,1,n,1,n);
		cout<<wy[n][k]<<"\n";
	}
    return 0;
}