#pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #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]; signed main() { cin.tie(0); ios::sync_with_stdio(0); int n, k; cin >> n >> k; string s[n]; ll c[n]; rep(i, n) { cin >> s[i] >> c[i]; } string t = string(k, 'J') + string(k, 'O') + string(k, '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; }