#include #include #include #include using namespace std ; const int MAXCOST = 1200 ; int counts[MAXCOST] ; void check(string &s, int &mindep, int &finaldep) { int dep = 0 ; mindep = 0 ; for (int i=0; i> n >> k >> s ; vector c(n) ; int basevalue = 0 ; for (int i=0; i> c[i] ; if (c[i] < 0) { c[i] = - c[i] ; basevalue += c[i] ; s[i] = '(' + ')' - s[i] ; } } int mindep, finaldep ; check(s, mindep, finaldep) ; int leftfix = (1-mindep) >> 1 ; int rightfix = (1+finaldep-mindep) >> 1 ; int fixcost = leftfix + rightfix ; if (fixcost > k || (n & 1)) { cout << (-basevalue) << endl ; exit(0) ; } int avail = 0 ; for (int i=0; i> 1 ; int rightfix = (1+finaldep-dep) >> 1 ; if (avail + leftfix + rightfix > k) { int totcost = 0 ; int need = k - leftfix - rightfix + 1 ; for (int ci=0; need > 0; ci++) { if (counts[ci]) { if (counts[ci] >= need) { totcost += ci * need ; break ; } else { totcost += ci * counts[ci] ; need -= counts[ci] ; } } } bestsol = min(bestsol, totcost) ; } if (i < n) { if (s[i] == ')') { dep-- ; counts[c[i]]-- ; avail-- ; } else { dep++ ; counts[c[i]]++ ; avail++ ; } } } if (bestsol == INT_MAX) cout << "?" << endl ; else cout << (bestsol - basevalue) << endl ; }