#include using namespace std; long long INF = 1000000000000000; 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]; } vector J(N); vector O(N); vector I(N); bool Jflg = false; bool Oflg = false; bool Iflg = false; for (int i = 0; i < N; i++){ for (char c : S[i]){ if (c == 'J'){ J[i]++; Jflg = true; } if (c == 'O'){ O[i]++; Oflg = true; } if (c == 'I'){ I[i]++; Iflg = true; } } } if (!(Jflg && Oflg && Iflg)){ cout << -1 << endl; } else { vector dpJ(K + 1, INF); dpJ[0] = 0; for (int i = 0; i < N; i++){ for (int j = 0; j < J[i]; j++){ dpJ[j] = min(dpJ[j], C[i]); } for (int j = J[i]; j <= K; j++){ dpJ[j] = min(dpJ[j], dpJ[j - J[i]] + C[i]); } } vector dpO(K + 1, INF); dpO[0] = 0; for (int i = 0; i < N; i++){ for (int j = 0; j < O[i]; j++){ dpO[j] = min(dpO[j], C[i]); } for (int j = O[i]; j <= K; j++){ dpO[j] = min(dpO[j], dpO[j - O[i]] + C[i]); } } vector dpI(K + 1, INF); dpI[0] = 0; for (int i = 0; i < N; i++){ for (int j = 0; j < I[i]; j++){ dpI[j] = min(dpI[j], C[i]); } for (int j = I[i]; j <= K; j++){ dpI[j] = min(dpI[j], dpI[j - I[i]] + C[i]); } } vector> Jcnt(N); //Jで左から累積和 for (int i = 0; i < N; i++){ Jcnt[i] = vector(S[i].size() + 1, 0); for (int j = 0; j < S[i].size(); j++){ if (S[i][j] == 'J'){ Jcnt[i][j + 1] = Jcnt[i][j] + 1; } else { Jcnt[i][j + 1] = Jcnt[i][j]; } } } vector> Ocnt1(N); //Oで左から累積和 for (int i = 0; i < N; i++){ Ocnt1[i] = vector(S[i].size() + 1, 0); for (int j = 0; j < S[i].size(); j++){ if (S[i][j] == 'O'){ Ocnt1[i][j + 1] = Ocnt1[i][j] + 1; } else { Ocnt1[i][j + 1] = Ocnt1[i][j]; } } } vector> Ocnt2(N); //Oで右から累積和 for (int i = 0; i < N; i++){ Ocnt2[i] = vector(S[i].size() + 1, 0); for (int j = S[i].size() - 1; j >= 0; j--){ if (S[i][j] == 'O'){ Ocnt2[i][j] = Ocnt2[i][j + 1] + 1; } else { Ocnt2[i][j] = Ocnt2[i][j + 1]; } } } vector> Icnt(N); //Iで右から累積和 for (int i = 0; i < N; i++){ Icnt[i] = vector(S[i].size() + 1, 0); for (int j = S[i].size() - 1; j >= 0; j--){ if (S[i][j] == 'I'){ Icnt[i][j] = Icnt[i][j + 1] + 1; } else { Icnt[i][j] = Icnt[i][j + 1]; } } } long long ans = INF; /* //A: J->O->I for (int i = 0; i < N; i++){ if (O[i] >= K){ vector Opos; for (int j = 0; j < S[i].size(); j++){ if (S[i][j] == 'O'){ Opos.push_back(j); } } for (int j = 0; j <= O[i] - K; j++){ int Jcurr = Jcnt[i][Opos[j]]; int Icurr = Icnt[i][Opos[j + K - 1] + 1]; long long cost = C[i]; if (Jcurr < K){ cost += dpJ[K - Jcurr]; } if (Icurr < K){ cost += dpI[K - Icurr]; } ans = min(ans, cost); } } } //B: J->O, O->I for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ for (int k = 0; k < S[i].size() + 1; k++){ for (int l = 0; l < S[j].size() + 1; l++){ int Jcurr = Jcnt[i][k]; int Ocurr = Ocnt2[i][k] + Ocnt1[j][l]; int Icurr = Icnt[j][l]; long long cost = C[i] + C[j]; if (Jcurr < K){ cost += dpJ[K - Jcurr]; } if (Ocurr < K){ cost += dpO[K - Ocurr]; } if (Icurr < K){ cost += dpI[K - Icurr]; } ans = min(ans, cost); } } } } */ cout << ans << endl; } }