/* https://yukicoder.me/problems/no/1029 個数無制限ナップザック? 部分文字列としてどこまで完成されているかを 0 ~ 3Kで表す? 各Kに関して、どの数字の時に何を足すといくつ増えるかをO(1)でだせれば あとはO(KN)の平易なdpでいける 適当に2分探索すれば行けるのでは?? */ #include using namespace std; #define rep(i,n,m) for(ll (i)=(n);(i)<(m);(i)++) #define rrep(i,n,m) for(ll (i)=(n);(i)>(m);(i)--) using ll = long long; const ll mod = 998244353; ll want(ll now,ll K,string& S){ rep(i,0,S.size()){ if ((now < K) && (S[i] == 'J')){ now++; }else if( (K <= now)&&(now < 2*K)&&(S[i]=='O' )){ now++; }else if( (2*K <= now) && (now < 3*K) && (S[i]=='I')){ now++; } } return now; } int main(){ ll N,K; cin >> N >> K; int flag = 0; vector S(N,""); vector C(N,0); rep(i,0,N){ cin >> S[i] >> C[i]; } vector JN(N,0); vector ON(N,0); vector IN(N,0); rep(i,0,N){ rep(j,0,S[i].size()){ if (S[i][j] == 'J') JN[i]++; if (S[i][j] == 'O') ON[i]++; if (S[i][j] == 'I') IN[i]++; } } vector ans(3*K+1,LLONG_MAX/5); ans[0] = 0; ll nex; rep(i,0,3*K){ rep(j,0,N){ if (i+JN[j] < K-1){ nex = i+JN[j]; }else if ( (K<=i) && (i+ON[j] < 2*K-1)){ nex = i+ON[j]; }else if ( i >= 2*K ){ nex = min(3*K,i+IN[j]); }else{ nex = want(i,K,S[j]); } ans[nex] = min(ans[nex] , ans[i] + C[j]); if (nex == 3*K) flag = 1; } } if (flag == 1){ cout << ans[3*K] << endl; }else{ cout << -1 << endl; } }