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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include <iostream>
#include <string.h>
#include <string>
#include <unordered_map>
#include <algorithm>


using namespace std;

using lli = long long int;


static int n, k;

static unordered_map<lli, lli> um;

static char aS[100002];

static lli  aC[100002];


static lli GetNawiasowosc(int iStart, int iEnd)
{
	if (iStart >= iEnd)
	{
		return 0;
	}

	lli iRet = 0;

	int iLevel = 0;
	int iFirst;

	for (int i = iStart; i <= iEnd; ++i)
	{
		aC[i] = 0;

		if (iLevel == 0 && aS[i] == ')')
			continue;

		if (iLevel == 0 && aS[i] == '(')
		{
			iFirst = i;
		}

		if (aS[i] == '(')
		{
			iLevel++;
			continue;
		}

		iRet++;
		iLevel--;

		if (iLevel > 0)
			continue;

		if (iFirst == iStart)
			continue;

		iRet += aC[iFirst - 1];

		aC[i] = aC[iFirst - 1] + 1;
	}

	return iRet;
}


static void ReadData()
{
	string s;

	cin >> n >> k >> s;

	strncpy(aS, s.c_str(), s.size());
}


static lli Recursive(int iStart, int iEnd, int iGroups)
{
	if ((iEnd - iStart + 1) <= iGroups)
	{
		return 0;
	}

	lli iHash = iStart;

	iHash = (iHash << 17) + iEnd;
	iHash = (iHash << 17) + iGroups;

	if (um.count(iHash) != 0)
	{
		return um[iHash];
	}

	if (iGroups == 1)
	{
		lli iRet = GetNawiasowosc(iStart, iEnd);

		um[iHash] = iRet;
		return iRet;
	}

	int iFirst = iStart;

	for (int i = iStart; i <= iEnd; ++i)
	{
		if (iEnd - i + 1 == iGroups)
		{
			um[iHash] = 0;
			return 0;
		}

		if (aS[i] == ')')
			continue;

		iFirst = i;
		break;
	}

	lli iRet = Recursive(iFirst + 1, iEnd, iGroups - 1);

	if (iRet == 0)
	{
		um[iHash] = 0;
		return 0;
	}

	for (int iStartOfThe2nd = iFirst + 2; iStartOfThe2nd <= iEnd; ++iStartOfThe2nd)
	{
		lli iCandidate = GetNawiasowosc(iFirst, iStartOfThe2nd - 1)
			           + Recursive(iStartOfThe2nd, iEnd, iGroups - 1);

		iRet = min(iRet, iCandidate);

		if (iRet == 0)
			break;
	}

	um[iHash] = iRet;
	return iRet;
}


static lli Solve()
{
	return Recursive(0, n - 1, k);
}


int main()
{
	ReadData();

	cout << Solve();
}