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
 92
 93
 94
 95
 96
 97
 98
 99
100
101
#include <bits/stdc++.h>
#define maxn 100005
#define ll long long
#define fi first
#define se second
#define inf 1000000000000000000ll
using namespace std;

char wej[maxn];
ll wyn;

ll ile[4005][4005];

ll pref[maxn];
ll stak[maxn];
void nawiasowosc(int poc, int kon)
{
	if(poc > kon) return;
	int it = 0;
	pref[poc-1] = 0;
	fill(stak, stak+kon-poc+2, 0ll);
	stak[0] = 1;
	for(int i = poc; i <= kon; ++i)
	{
		pref[i] = pref[i-1];
		if(wej[i] == '(') stak[++it] = 1;
		else
		{
			--it;
			if(it >= 0) pref[i] += stak[it];
			else it = 0, stak[it] = 0;
			++stak[it];
		}
	}
}

pair <ll, ll> dp[maxn];

int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	
	int n, k;
	cin >> n >> k;
	for(int i = 1; i <= n; ++i) cin >> wej[i];
	
	if(n > 4000)
	{
		ll poc = 0;
		ll kon = ((ll)n)*((ll)n)+5ll;
		while(poc <= kon)
		{
			ll sr = (poc+kon)>>1;
			
			for(int i = 0; i <= n; ++i) dp[i] = {inf, 0ll};
			dp[0] = {0ll, 0ll};
			for(int i = 0; i < n; ++i)
			{
				nawiasowosc(i+1, n);
				for(int j = i+1; j <= n; ++j)
				{
					ll t = dp[i].fi+sr+pref[j];
					if(t < dp[j].fi) dp[j].fi = t, dp[j].se = dp[i].se+1ll;
				}
			}
			
			if(dp[n].se <= k) wyn = dp[n].fi - ((ll)k)*sr, kon = sr-1ll;
			else poc = sr+1ll;
		}
		cout << wyn;
		return 0;
	}
	
	for(int i = 1; i <= n; ++i)
	{
		nawiasowosc(i, n);
		for(int j = i; j <= n; ++j) ile[i][j] = pref[j];
	}
	
	ll poc = 0;
	ll kon = ((ll)n)*((ll)n)+5ll;
	while(poc <= kon)
	{
		ll sr = (poc+kon)>>1;
		
		for(int i = 0; i <= n; ++i) dp[i] = {inf, 0ll};
		dp[0] = {0ll, 0ll};
		for(int i = 0; i < n; ++i) for(int j = i+1; j <= n; ++j)
		{
			ll t = dp[i].fi+sr+ile[i+1][j];
			if(t < dp[j].fi) dp[j].fi = t, dp[j].se = dp[i].se+1ll;
		}
		
		if(dp[n].se <= k) wyn = dp[n].fi - ((ll)k)*sr, kon = sr-1ll;
		else poc = sr+1ll;
	}
	cout << wyn;
	
	return 0;
}