#include #define rep(i,n) for (ll i = 0; i < n; ++i) #define sz(x) int(x.size()) #define ALL(c) (c).begin(), (c).end() #define SUM(x) std::accumulate(ALL(x), 0LL) #define MIN(v) *std::min_element(v.begin(), v.end()) #define MAX(v) *std::max_element(v.begin(), v.end()) #define EXIST(v, x) (std::find(v.begin(), v.end(), x) != v.end()) #define FORV(i, v) for (auto i = v.begin(); i != v.end(); i++) using namespace std; using ll = int64_t; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; } const int INF = 1001001001; const long long INFL = LLONG_MAX / 2; const double eps = (1e-9); int main() { cin.tie(0); ios::sync_with_stdio(false); ll n, k; cin >> n >> k; vector s(n); vector c(n); rep(i, n) cin >> s[i] >> c[i]; vector> wj(n, vector()); // 先頭から idx の位置までに J が何個あるか vector> wo(n, vector()); vector> wi(n, vector()); rep(i, n) { wj[i].resize(s[i].size(), 0); wo[i].resize(s[i].size(), 0); wi[i].resize(s[i].size(), 0); if (s[i][0] == 'J') wj[i][0] = 1; if (s[i][0] == 'O') wo[i][0] = 1; if (s[i][0] == 'I') wi[i][0] = 1; for (int j = 1; j < s[i].size(); j++) { if (s[i][j] == 'J') wj[i][j] = wj[i][j-1] + 1; else wj[i][j] = wj[i][j-1]; if (s[i][j] == 'O') wo[i][j] = wo[i][j-1] + 1; else wo[i][j] = wo[i][j-1]; if (s[i][j] == 'I') wi[i][j] = wi[i][j-1] + 1; else wi[i][j] = wi[i][j-1]; } } vector dp(3*k+5, INFL); dp[0] = 0; for (ll x = 0; x < 3*k; x++) { ll r_j = max(ll(0), k - x); // x に居るときに残りの必要なJ ll r_o = x >= 2 * k ? 0 : max(ll(0), min(k, 2 * k - x)); // x に居るときに残りの必要なO ll r_i = max(3 * k - x, k); // x に居るときに残りの必要なI for (int y = 0; y < n; y++) { ll idx_dp = x; // 今 x に居て s_y を使用したときにどこに遷移するか? ll idx_y = 0; // s_y の何文字目まで使用したか if (r_j > 0) { auto itr = lower_bound(ALL(wj[y]), r_j); if (itr == wj[y].end()) { idx_y = s[y].size(); idx_dp += wj[y].back(); } else { idx_y = itr - wj[y].begin(); idx_dp = k; } } if (r_o > 0 && idx_y != s[y].size()) { if (idx_y > 0) r_o += wo[y][idx_y]; auto itr = lower_bound(ALL(wo[y]), r_o); if (itr == wo[y].end()) { idx_dp += wo[y].back(); if (idx_y > 0) idx_dp -= wo[y][idx_y]; idx_y = s[y].size(); } else { idx_y = itr - wo[y].begin(); idx_dp = 2 * k; } } if (idx_y != s[y].size()) { if (idx_y > 0) idx_dp = idx_dp + wi[y].back() - wi[y][idx_y]; else idx_dp = idx_dp + wi[y].back(); chmin(idx_dp, 3*k); } if (idx_dp == x) continue; chmin(dp[idx_dp], dp[x] + c[y]); } } if (dp[3*k] == INFL) puts("-1"); else cout << dp[3 * k] << endl; return 0; }