#include using namespace std; #define DEBUG(x) cerr<<#x<<": "< #define vl vector #define vii vector< vector > #define vll vector< vector > #define vs vector #define pii pair #define pis pair #define psi pair #define pll pair template pair operator+(const pair &s, const pair &t) { return pair(s.first + t.first, s.second + t.second); } template pair operator-(const pair &s, const pair &t) { return pair(s.first - t.first, s.second - t.second); } template ostream& operator<<(ostream& os, pair p) { os << "(" << p.first << ", " << p.second << ")"; return os; } #define X first #define Y second #define rep(i,n) for(int i=0;i<(int)(n);i++) #define rep1(i,n) for(int i=1;i<=(int)(n);i++) #define rrep(i,n) for(int i=(int)(n)-1;i>=0;i--) #define rrep1(i,n) for(int i=(int)(n);i>0;i--) #define REP(i,a,b) for(int i=a;i bool chmax(T &a, const T &b) { if (a bool chmin(T &a, const T &b) { if (a>b) { a = b; return 1; } return 0; } #define UNIQUE(v) v.erase(std::unique(v.begin(), v.end()), v.end()); const ll inf = 1000000001; const ll INF = (ll)1e18 + 1; const long double pi = 3.1415926535897932384626433832795028841971L; #define Sp(p) cout< s; vl c; vii J(N), O(N), I(N); vll calc_dp(vii num) { vll dp(n + 1, vl(k + 82, INF)); dp[0][0] = 0; rep1 (i, n) { rep (j, k + 82) { chmin(dp[i][j], dp[i - 1][j]); if (num[i - 1].back() > 0 and j - num[i - 1].back() >= 0) { chmin(dp[i][j], dp[i - 1][j - num[i - 1].back()] + c[i - 1]); chmin(dp[i][j], dp[i][j - num[i - 1].back()] + c[i - 1]); } } } ll mi = INF; rrep (j, k + 82) { chmin(mi, dp[n][j]); dp[n][j] = mi; } return dp; } signed main() { fio(); cin >> n >> k; s.resize(n); c.resize(n); bool flagI, flagJ, flagO; rep (i, n) { cin >> s[i] >> c[i]; rep (j, s[i].size()) { if (s[i][j] == 'J') flagJ = true; else if (s[i][j] == 'O') flagO = true; else flagI = true; } } if (not flagI or not flagJ or not flagO) { cout << -1 << endl; return 0; } rep (i, n) { J[i].resize(s[i].size() + 1); O[i].resize(s[i].size() + 1); I[i].resize(s[i].size() + 1); for (int j = 0; j < s[i].size(); j++) { J[i][j + 1] += J[i][j]; O[i][j + 1] += O[i][j]; I[i][j + 1] += I[i][j]; if (s[i][j] == 'J') J[i][j + 1]++; else if (s[i][j] == 'O') O[i][j + 1]++; else I[i][j + 1]++; } } // DEBUG_MAT(J); // DEBUG_MAT(O); // DEBUG_MAT(I); vll dpj = calc_dp(J); vll dpo = calc_dp(O); vll dpi = calc_dp(I); // DEBUG_MAT(dpj); // DEBUG_MAT(dpo); // DEBUG_MAT(dpi); ll mi = INF; rep (i, n) { for (int j = 0; j <= s[i].size(); j++) { rep (l, n) { for (int m = 0; m <= s[l].size(); m++) { ll ans = c[i] + c[l]; ll fu_J = max(0LL, k - J[i][j]); ll fu_O = max(0LL, k - (O[i].back() - O[i][j]) - O[l][m]); ll fu_I = max(0LL, k - (I[l].back() - I[l][m])); ans += dpj[n][fu_J] + dpo[n][fu_O] + dpi[n][fu_I]; chmin(mi, ans); } } } } cout << mi << endl; }