#define _USE_MATH_DEFINES #include using namespace std; map conv = {{'J', 0}, {'O', 1}, {'I', 2}}; signed main() { ios::sync_with_stdio(false); cin.tie(0); int n, k; cin >> n >> k; vector goal = {-1}; for (int i = 0; i < 3; i++) for (int j = 0; j < k; j++) goal.push_back(i); vector> s; vector cost; vector> cnt; for (int i = 0; i < n; i++) { string t; cin >> t; int c; cin >> c; vector tmp; for (auto& ch : t) if (conv.count(ch)) tmp.push_back(conv[ch]); if (tmp.empty()) continue; vector cc(3); for (auto& i : tmp) cc[i]++; s.push_back(tmp); cost.push_back(c); cnt.push_back(cc); } n = s.size(); vector dp(1 + 3 * k, 1LL << 60); dp[0] = 0; for (int cur = 1; cur <= 3 * k; cur++) { for (int i = 0; i < n; i++) { int to = min(3 * k, cur + (int) s[i].size() - 1); if (goal[cur] == goal[to]) { int x = goal[cur]; to = min(3 * k, cur + cnt[i][x] - 1); dp[to] = min(dp[to], dp[cur - 1] + cost[i]); } else { to = cur; for (auto& j : s[i]) { if (to <= 3 * k && goal[to] == j) to++; } to--; dp[to] = min(dp[to], dp[cur - 1] + cost[i]); } } } cout << (dp[3 * k] == 1LL << 60 ? -1 : dp[3 * k]) << endl; return 0; }