/* -*- coding: utf-8 -*- * * 1029.cc: No.1029 JJOOII 3 - yukicoder */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; /* constant */ const int MAX_N = 80; const int MAX_S = 80; const int CN = 3; const int MAX_K = 100000; const long long LINF = 1LL << 62; enum { J, O, I, FIN }; /* typedef */ typedef long long ll; typedef pair pii; /* global variables */ int cmap[128]; char s[MAX_S + 4]; int cs[MAX_N], scs[CN][MAX_S], scns[CN]; pii ps[MAX_N][CN + 1][MAX_K]; ll dp[CN + 1][MAX_K]; /* subroutines */ inline void setmin(ll &a, ll b) { if (a > b) a = b; } /* main */ int main() { cmap['J'] = J, cmap['O'] = O, cmap['I'] = I; int n, k; scanf("%d%d", &n, &k); for (int i = 0; i < n; i++) { scanf("%s%d", s, cs + i); int sn = strlen(s); memset(scns, 0, sizeof(scns)); for (int j = 0; j < sn; j++) { int sj = cmap[s[j]]; scs[sj][scns[sj]++] = j; } for (int l = 0; l < k; l++) ps[i][FIN][l] = pii(FIN, 0); for (int j = FIN - 1; j >= 0; j--) for (int l = k - 1; l >= 0; l--) { int z = j, y = l, x = 0; while (z < FIN) { int q = lower_bound(scs[z], scs[z] + scns[z], x) - scs[z]; int yy = y + (scns[z] - q); if (yy < k) { ps[i][j][l] = pii(z, yy); break; } int xq = q + (k - y); x = scs[z][xq - 1] + 1; y = 0; z++; } if (z == FIN) ps[i][j][l] = pii(FIN, 0); } //printf("%d\n", i); //for (int j = 0; j <= FIN; j++) { //for (int l = 0; l < k; l++) //printf(" (%d,%d)", ps[i][j][l].first, ps[i][j][l].second); //putchar('\n'); //} } for (int j = 0; j <= FIN; j++) fill(dp[j], dp[j] + k, LINF); dp[0][0] = 0; for (int j = 0; j < FIN; j++) for (int l = 0; l < k; l++) if (dp[j][l] < LINF) for (int i = 0; i < n; i++) { int j1 = ps[i][j][l].first, l1 = ps[i][j][l].second; if (j1 != j || l1 != l) setmin(dp[j1][l1], dp[j][l] + cs[i]); } printf("%lld\n", (dp[FIN][0] >= LINF) ? -1 : dp[FIN][0]); return 0; }