#include"bits/stdc++.h" using namespace std; #define int long long #define rep(i,n) for(int i=0;i=l[i][j])dp[i][j + 1][k] = min(dp[i][j + 1][k], dp[i][j+1][k-l[i][j]] + c[j]); } } rep(k, 100100)dp[i][n][k] = min(dp[i][n][k], dp[i][n][k + 1]); } } signed main() { cin.tie(0); ios::sync_with_stdio(false); cin >> n >> K; int ej = 0, eo = 0, ei = 0; rep(i, n) { cin >> s[i] >> c[i]; rep(j, s[i].size()) { if (s[i][j] == 'J') { l[0][i]++; rwa[0][i][j + 1]++; } if (s[i][j] == 'O') { l[1][i]++; rwa[1][i][j + 1]++; } if (s[i][j] == 'I') { l[2][i]++; rwa[2][i][j + 1]++; } } ej += l[0][i]; eo += l[1][i]; ei += l[2][i]; rep(j, s[i].size()) { rep(k, 3) { rwa[k][i][j + 1] += rwa[k][i][j]; } } } if (!ej || !eo || !ei) { cout << -1 << endl; return 0; } memo(); int ans = inf; rep(i, n) {//文字列1個 rep(j, s[i].size()) { for (int k = j; k < s[i].size(); k++) { if (rwa[1][i][k + 1] - rwa[1][i][j] < K)continue; int jr = max(0ll, K - rwa[0][i][j]); int ji = max(0ll, K - rwa[2][i][s[i].size()] + rwa[2][i][k+1]); ans = min(ans, c[i] + dp[0][n][jr] + dp[2][n][ji]); } } } rep(i, n) { rep(j, n) {//文字列2個 rep(k, s[i].size() + 1) { rep(l, s[j].size() + 1) { int jr = max(0ll, K - rwa[0][i][k]); int jo = max(0ll, K - rwa[1][i][s[i].size()]+rwa[1][i][k] - rwa[1][j][l]); int ji = max(0ll, K - rwa[2][j][s[j].size()]+rwa[2][j][l]); ans = min(ans, c[i] + c[j] + dp[0][n][jr] + dp[1][n][jo] + dp[2][n][ji]); } } } } cout << ans << endl; }