#include #define rep(i,n) for(int i = 0; i < (n); ++i) #define srep(i,s,t) for (int i = s; i < t; ++i) #define drep(i,n) for(int i = (n)-1; i >= 0; --i) using namespace std; typedef long long int ll; typedef pair P; #define yn {puts("YES");}else{puts("NO");} #define MAX_N 200005 int main() { int n, k; cin >> n >> k; string s[n]; ll c[n]; rep(i,n)cin >> s[i] >> c[i]; ll dp[k*3]; rep(i,k*3)dp[i] = 1001001001001001001; int f[n][3] = {}; int m[n]; rep(i,n){ m[i] = s[i].size(); rep(j,n){ if(s[i][j] == 'J')f[i][0]++; if(s[i][j] == 'O')f[i][1]++; if(s[i][j] == 'I')f[i][2]++; } } rep(i,k*3){ rep(j,n){ if(k > 200 && 100 <= i && i < k){ dp[i] = min(dp[i], dp[i-f[j][0]] + c[j]); }else if(k > 200 && k + 100 <= i && i < k*2){ dp[i] = min(dp[i], dp[i-f[j][1]] + c[j]); }else if(k > 200 && k*2 + 100 <= i && i < k*3){ dp[i] = min(dp[i], dp[i-f[j][2]] + c[j]); }else{ int now = i; drep(l,m[j]){ if(now == -1)break; char x = 'J'; if(now >= k)x = 'O'; if(now >= k*2)x = 'I'; if(s[j][l] == x)now--; } if(now == -1)dp[i] = min(dp[i], c[j]); else dp[i] = min(dp[i], dp[now] + c[j]); } } } ll ans = dp[k*3-1]; if(ans == 1001001001001001001)ans = -1; cout << ans << endl; return 0; }