#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> N >> K; vector S(N); vector C(N); REP(i, N) cin >> S[i] >> C[i]; vector cost(K * 3 + 1, 9e18); cost[0] = 0; REP(i, K * 3) if (cost[i] < cost[i + 1]) { REP(j, N) { 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'; }