#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); for (int i = 0; i < n; ++i) { cin >> s[i] >> cost[i]; } for (int j = m; j--; ) { for (int i = 0; i < n; ++i) { int ptr = j; 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'; }