#include using namespace std; #ifdef LOCAL #include "debug.h" #else #define DEBUG(...) #endif template constexpr T inf = numeric_limits::max() / 2.1; auto chmin = [](auto&& a, auto b) { return b < a ? a = b, 1 : 0; }; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n, k; cin >> n >> k; string t = string(k, 'J') + string(k, 'O') + string(k, 'I'); int m = t.size(); vector dp(m + 1, inf); dp[m] = 0; vector s(n); vector cost(n); vector> cnt(n); for (int i = 0; i < n; ++i) { cin >> s[i] >> cost[i]; cnt[i][0] = count(begin(s[i]), end(s[i]), 'J'); cnt[i][1] = count(begin(s[i]), end(s[i]), 'O'); cnt[i][2] = count(begin(s[i]), end(s[i]), 'I'); } for (int j = m; j--; ) { for (int i = 0; i < n; ++i) { int ptr = j; if (j >= 2 * k) { ptr = min(ptr + cnt[i][2], m); } else if (k <= j and j < 2 * k and j + cnt[i][1] < 2 * k) { ptr += cnt[i][1]; } else if (j < k and j + cnt[i][0] < k) { ptr += cnt[i][0]; } else { for (char c : s[i]) { if (ptr < m) { ptr += c == t[ptr]; } } } chmin(dp[j], cost[i] + dp[ptr]); } } if (dp[0] >= inf) { dp[0] = -1; } cout << dp[0] << '\n'; }