#include using namespace std; using ll = long long; #define rep(i, n) for (int i = 0; i < (n); i++) #define repr(i, n) for (int i = (n) - 1; i >= 0; i--) #define range(a) a.begin(), a.end() int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int N, K; cin >> N >> K; vector dp(3 * K + 1, LLONG_MAX); dp[0] = 0; vector S(N); vector C(N); rep(i, N) cin >> S[i] >> C[i]; rep(i, 3 * K) if (dp[i] != LLONG_MAX) { rep(j, N) { int l = i; for (char c : S[j]) { if (l < K) { if (c == 'J') l++; } else if (l < 2 * K) { if (c == 'O') l++; } else if (l < 3 * K) { if (c == 'I') l++; } } dp[l] = min(dp[l], dp[i] + C[j]); } } if (dp[3 * K] == LLONG_MAX) { cout << -1 << endl; } else { cout << dp[3 * K] << endl; } }