#include #define rep(i,a,b) for(int i=a;i=b;i--) #define fore(i,a) for(auto &i:a) #define all(x) (x).begin(),(x).end() //#pragma GCC optimize ("-O3") using namespace std; void _main(); int main() { cin.tie(0); ios::sync_with_stdio(false); _main(); } typedef long long ll; const int inf = INT_MAX / 2; const ll infl = 1LL << 60; templatebool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; } templatebool chmin(T& a, const T& b) { if (b < a) { a = b; return 1; } return 0; } //--------------------------------------------------------------------------------------------------- /*---------------------------------------------------------------------------------------------------             ∧_∧       ∧_∧  (´<_` )  Welcome to My Coding Space!      ( ´_ゝ`) /  ⌒i @hamayanhamayan0     /   \    | |     /   / ̄ ̄ ̄ ̄/  |   __(__ニつ/  _/ .| .|____      \/____/ (u ⊃ ---------------------------------------------------------------------------------------------------*/ int N, K; string S[80]; int C[80]; ll dp[4][101010]; //--------------------------------------------------------------------------------------------------- string JOI = "JOI"; int joicnt[80][3]; pair memo[3][81][80]; pair get(int joi, int cnt, int i) { if (joicnt[i][joi] < K - cnt) return { joi, cnt + joicnt[i][joi] }; if (0 <= memo[joi][K - cnt][i].first) return memo[joi][K - cnt][i]; pair& m = memo[joi][K - cnt][i]; fore(c, S[i]) { if (JOI[joi] == c) { cnt++; if (cnt == K) { joi++; cnt = 0; if (joi == 3) return m = { 3, 0 }; } } } return m = { joi, cnt }; } //--------------------------------------------------------------------------------------------------- void _main() { cin >> N >> K; rep(i, 0, N) cin >> S[i] >> C[i]; rep(i, 0, N) fore(c, S[i]) rep(j, 0, 3) if (c == JOI[j]) joicnt[i][j]++; rep(joi, 0, 4) rep(cnt, 0, K + 1) dp[joi][cnt] = infl; dp[0][0] = 0; rep(joi, 0, 3) rep(rest, 0, 81) rep(i, 0, N) memo[joi][rest][i].first = -1; rep(joi, 0, 3) rep(cnt, 0, K) if(dp[joi][cnt] < infl) rep(i, 0, N) { int joi2, cnt2; tie(joi2, cnt2) = get(joi, cnt, i); chmin(dp[joi2][cnt2], dp[joi][cnt] + C[i]); } if (dp[3][0] == infl) cout << -1 << endl; else cout << dp[3][0] << endl; }