#include using namespace std; using lint = long long int; struct fast_ios { fast_ios(){ cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; } fast_ios_; #define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i bool chmin(T &m, const T q) { if (m > q) {m = q; return true;} else return false; } int main() { int N, K; cin >> N >> K; vector S(N); vector C(N); REP(i, N) cin >> S[i] >> C[i]; vector cntj(N), cnto(N), cnti(N); REP(i, N) for (auto c : S[i]) { if (c == 'J') cntj[i]++; if (c == 'O') cnto[i]++; if (c == 'I') cnti[i]++; } vector cost(K * 3 + 1, 9e18); cost[0] = 0; REP(i, K * 3) if (cost[i] < cost[i + 1]) { REP(j, N) { if (i + 100 < K) chmin(cost[i + cntj[j]], cost[i] + C[j]); else if (i >= K and i + 100 < K * 2) chmin(cost[i + cnto[j]], cost[i] + C[j]); else if (i >= K * 2 and i + 100 < K * 3) chmin(cost[i + cnti[j]], cost[i] + C[j]); else { int now = i; for (auto c : S[j]) { if (now < K and c == 'J') now++; if (now >= K and now < K * 2 and c == 'O') now++; if (now >= K * 2 and now < K * 3 and c == 'I') now++; } cost[now] = min(cost[now], cost[i] + C[j]); } } } cout << (cost.back() == 9e18 ? -1 : cost.back()) << '\n'; }