#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; signed main() { int n, k; cin >> n >> k; string s[n]; ll c[n]; rep(i, n) { cin >> s[i] >> c[i]; } string t; rep(i, k) { t.push_back('J'); } rep(i, k) { t.push_back('O'); } rep(i, k) { t.push_back('I'); } ll dp[3 * k + 1]; 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; }