#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; constexpr int INF = 1001001001; constexpr int mod = 1000000007; // constexpr int mod = 998244353; template inline bool chmax(T& x, T y){ if(x < y){ x = y; return true; } return false; } template inline bool chmin(T& x, T y){ if(x > y){ x = y; return true; } return false; } ll dp[300005]; int sum[100][3][100]; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int N, K; cin >> N >> K; vector S(N); vector C(N), L(N); for(int i = 0; i < N; ++i){ cin >> S[i] >> C[i]; L[i] = S[i].length(); for(int j = 0; j < L[i]; ++j){ if(S[i][j] == 'J') sum[i][0][j + 1] = 1; else if(S[i][j] == 'O') sum[i][1][j + 1] = 1; else sum[i][2][j + 1] = 1; } for(int j = 0; j < 3; ++j){ for(int k = 0; k < L[i]; ++k){ sum[i][j][k + 1] += sum[i][j][k]; } } } constexpr ll inf = 1e+17; for(int i = 0; i <= K * 3; ++i) dp[i] = inf; dp[0] = 0; for(int i = 0; i < K; ++i){ if(dp[i] == inf) continue; for(int j = 0; j < N; ++j){ if(i + sum[j][0][L[j]] < K){ chmin(dp[i + sum[j][0][L[j]]], dp[i] + C[j]); } else{ int rest = K - i; for(int k = 0; k < L[j]; ++k){ if(S[j][k] == 'J' && --rest == 0){ int nk = K + sum[j][1][L[j]] - sum[j][1][k]; if(nk < K * 2){ chmin(dp[K + sum[j][1][L[j]] - sum[j][1][k]], dp[i] + C[j]); } else{ rest = K; for(int l = k; l < L[j]; ++l){ if(S[j][l] == 'O' && --rest == 0){ chmin(dp[K * 2 + sum[j][2][L[j]] - sum[j][2][l]], dp[i] + C[j]); break; } } } break; } } } } } for(int i = K; i < K * 2; ++i){ if(dp[i] == inf) continue; for(int j = 0; j < N; ++j){ if(i + sum[j][1][L[j]] < K * 2){ chmin(dp[i + sum[j][1][L[j]]], dp[i] + C[j]); } else{ int rest = K * 2 - i; for(int k = 0; k < L[j]; ++k){ if(S[j][k] == 'O' && --rest == 0){ chmin(dp[K * 2 + sum[j][2][L[j]] - sum[j][2][k]], dp[i] + C[j]); break; } } } } } for(int i = K * 2; i < K * 3; ++i){ if(dp[i] == inf) continue; for(int j = 0; j < N; ++j){ chmin(dp[min(K * 3, i + sum[j][2][L[j]])], dp[i] + C[j]); } } ll ans = dp[K * 3]; if(ans == inf) ans = -1; cout << ans << endl; return 0; }