#pragma warning (disable: 4996) #include "bits/stdc++.h" using namespace std; #define rep(i,n) for(int i=0;i> n >> K; rep(i, n)cin >> s[i] >> c[i]; } int solve() { input(); rep(i, n) { siz[i] = s[i].size(); rep(j, siz[i]) { if (s[i][j] == 'J')cr[i][j + 1][0]++; if (s[i][j] == 'O')cr[i][j + 1][1]++; if (s[i][j] == 'I')cr[i][j + 1][2]++; } rep(j, siz[i]) { rep(k, 3) { cr[i][j + 1][k] += cr[i][j][k]; } } } rep(k, 3) { rep(i, n + 1)rep(j, K + 100)dp[k][i][j] = inf; dp[k][0][0] = 0; rep(i, n) { rep(j, K + 100) { dp[k][i + 1][j] = dp[k][i][j]; int v = cr[i][siz[i]][k]; if (j >= v)dp[k][i + 1][j] = min(dp[k][i + 1][j], dp[k][i + 1][j - v] + c[i]); } } for (int j = K + 90; j > 0; j--)dp[k][n][j - 1] = min(dp[k][n][j], dp[k][n][j - 1]); // rep(j, K + 1)cout << dp[k][n][j] << ' '; cout << endl; } int ans = inf; //中央に1個使う rep(i, n) { if (cr[i][siz[i]][1] < K)continue; int res = c[i]; rep(j, siz[i]) { for (int k = j; k < siz[i]; k++) { if (cr[i][k + 1][1] - cr[i][j][1] < K)continue; int cst = c[i]; int J = cr[i][j][0], I = cr[i][siz[i]][2] - cr[i][k][2]; if (J < K)cst += dp[0][n][K - J]; if (I < K)cst += dp[2][n][K - I]; ans = min(ans, cst); } } } //中央に2個使う /* rep(i, n) { rep(j, n) { rep(k, siz[i] + 1) { rep(l, siz[j] + 1) {//~k-1][k~l-1][l~ int cst = c[i] + c[j]; int J = cr[i][k][0], O = cr[i][siz[i]][1] - cr[i][k][1] + cr[j][l][1], I = cr[j][siz[j]][2] - cr[j][l][2]; if (J < K)cst += dp[0][n][K - J]; if (O < K)cst += dp[1][n][K - O]; if (I < K)cst += dp[2][n][K - I]; ans = min(ans, cst); } } } }*/ if (ans >= inf)ans = -1; return ans; } signed main() { cout << solve() << endl; }