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
#include <cstdio>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <sstream>
#include <iostream>
#include <map>
#include <cmath>
#include <set>
#include <queue>
#include <numeric>
#include <ctime>
#include <sys/time.h>

using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
#define INF 1000000000
#define SZ(v) ((int)(v).size())
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define FORE(i,a,b) for(int i=(a);i<=(b);i++)
#define FS first
#define SD second
#define MP make_pair
#define ZERO(t) memset(t, 0, sizeof(t))
#define MINUS(t) memset(t, -1, sizeof(t))
#define MOD 1000000007
#define MIN(_a,_b) ((_a)<(_b)?(_a):(_b))
#define MAX(_a,_b) ((_a)>(_b)?(_a):(_b))


int* NAW[100000];
char S[100000];
int H[100000];
int* D[100000];


void go(int left, int right, int p_min, int p_max, int k) {
  if (left > right) return;
 
  int mid = (left + right) / 2;
  int best = INF;
  int p = -1;
  
  for (int i = p_min; i <= min(mid, p_max); ++i) {
    int cand = (i < k ? 0 : D[i - 1][k - 1]) + NAW[i][mid];
    if (cand < best) {
      best = cand;
      p = i;
    }
  }
  D[mid][k] = best;
  go(left, mid - 1, p_min, p, k);
  go(mid + 1, right, p, p_max, k);
}


int main() {
  int n, k; scanf("%d%d", &n, &k);
  FOR(i,0,n) {
    NAW[i] = new int[n];
    D[i] = new int[k+1];
  }
  scanf("%s", S);
  
  FOR(i,0,n) {
    ZERO(H);
    int h = n;
    H[h] = 1;
    FOR(j,i,n) {
      if (i == j) NAW[i][j] = 0;
      else NAW[i][j] = NAW[i][j - 1];
      if (S[j] == '(') {
        ++h;
        H[h] = 1;
      }
      else {
        --h;
        NAW[i][j] += H[h];
        H[h]++;
      }
    }
  }

  FOR(i,0,n) {
    D[i][1] = NAW[0][i];
  }
  
  FORE(kk,2,k) {
    go(kk - 1, n - 1, kk - 2, n - 1, kk);
  }

  
  printf("%d\n", D[n-1][k]);
}