#include #define all(vec) vec.begin(), vec.end() #define pb push_back #define eb emplace_back using namespace std; using ll = long long; using P = pair; template using V = vector; constexpr ll INF = (1LL << 60) - 1LL; constexpr ll MOD = 998244353LL; constexpr int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; template void chmin(T &a, T b) { a = min(a, b); } template void chmax(T &a, T b) { a = max(a, b); } void debug() { cerr << "ok" << endl; } template void vout(const vector &v) { for (int i = 0; i < v.size(); i++) { cout << v[i] << (i + 1 == v.size() ? '\n' : ' '); } } int main() { ios::sync_with_stdio(0); cin.tie(0); int n, K; cin >> n >> K; V s(n); V c(n); for (int i = 0; i < n; i++) { cin >> s[i] >> c[i]; } auto calc = [&](char cc) { V> dp(n + 1, V(K + 200, INF)); dp[0][0] = 0; for (int i = 0; i < n; i++) { int co = 0; for (auto &e : s[i]) { if (e == cc) { co++; } } for (int j = 0; j <= K + 100; j++) { chmin(dp[i + 1][j], dp[i][j]); if (j >= co) { chmin(dp[i + 1][j], dp[i + 1][j - co] + c[i]); } } } return dp[n]; }; V dpj = calc('J'), dpo = calc('O'), dpi = calc('I'); for (int i = K; i >= 0; i--) { chmin(dpj[i], dpj[i + 1]); chmin(dpo[i], dpo[i + 1]); chmin(dpi[i], dpi[i + 1]); } V> cco(n), cci(n), ccj(n); ll res = INF; for (int i = 0; i < n; i++) { cco[i].resize(s[i].size() + 1); cci[i].resize(s[i].size() + 1); ccj[i].resize(s[i].size() + 1); for (int j = 0; j < s[i].size(); j++) { ccj[i][j + 1] = ccj[i][j]; cco[i][j + 1] = cco[i][j]; cci[i][j + 1] = cci[i][j]; if (s[i][j] == 'J') { ccj[i][j + 1]++; } else if (s[i][j] == 'O') { cco[i][j + 1]++; } else { cci[i][j + 1]++; } } } for (int i = 0; i < n; i++) { int cj = 0; for (int j = 0; j < s[i].size(); j++) { int co = 0; for (int k = j; k < s[i].size(); k++) { if (s[i][k] == 'O') co++; if (co >= K) { int toj = K - cj, toi = K - (cci[i][s[i].size()] - cci[i][k]); chmax(toj, 0); chmax(toi, 0); if (dpj[toj] != INF && dpi[toi] != INF) { chmin(res, dpj[toj] + dpi[toi] + c[i]); } } } if (s[i][j] == 'J') { cj++; } } cj = 0; for (int j = 0; j < s[i].size(); j++) { int co = cco[i][s[i].size()] - cco[i][j]; for (int k = 0; k < n; k++) { int co2 = 0; for (int l = 0; l < s[k].size(); l++) { if (s[k][l] == 'O') { co2++; } int toj = K - cj, toi = K - (cci[k][s[k].size()] - cci[k][l]), too = K - co - co2; chmax(toj, 0); chmax(toi, 0); chmax(too, 0); if (dpj[toj] != INF && dpi[toi] != INF && dpo[too] != INF) { chmin(res, c[i] + c[k] + dpj[toj] + dpi[toi] + dpo[too]); } } } if (s[i][j] == 'J') { cj++; } } } cout << (res == INF ? -1LL : res) << '\n'; }