#include using namespace std; #define rep(i, n) for (int i = 0; i < (n); i++) #define ALL(v) (v).begin(), (v).end() using ll = long long; using P = pair; constexpr int INF = 1e9; constexpr long long LINF = 1e18; constexpr long long MOD = 1e9 + 7; ll dp[300000 + 1]; int k; char t(int n) { if (n < k) return 'J'; else if (n < 2 * k) return 'O'; else return 'I'; } signed main() { cin.tie(0); ios::sync_with_stdio(0); int n; cin >> n >> k; string s[n]; ll c[n]; rep(i, n) { cin >> s[i] >> c[i]; } fill(dp, dp + 3 * k + 1, LINF); dp[0] = 0; rep(i, 3 * k) { rep(j, n) { int now = 0; rep(l, s[j].size()) { if (s[j][l] == t(i + now)) { now++; dp[i + now] = min(dp[i + now], dp[i] + c[j]); } } } } cout << (dp[3 * k] != LINF ? dp[3 * k] : -1) << endl; return 0; }