#include #include #include #include #include using namespace std; int main() { int N, K; cin >> N >> K; vector S(N); vector C(N); for (int i = 0; i < N; ++i) { cin >> S[i] >> C[i]; } string JOI(K, 'J'); JOI += string(K, 'O'); JOI += string(K, 'I'); long long inf = 1ll<<60; vector dp(3 * K + 1, inf); dp[0] = 0; for (int k0 = 0; k0 <= 3 * K; ++k0) { for (int n = 0; n < N; ++n) { int k1 = k0; for (char s : S[n]) { if (k1 < 3 * K && JOI[k1] == s) { ++k1; } } dp[k1] = min(dp[k1], dp[k0] + C[n]); } } long long ans = dp[3 * K]; if (ans == inf) { ans = -1; } cout << ans << endl; return 0; }