#include #include #include #include template std::vector vec(int len, T elem) { return std::vector(len, elem); } using lint = long long; constexpr lint INF = 1LL << 60; const std::string JOI = "JOI$"; void solve() { int n, k; std::cin >> n >> k; std::vector> ps(n); for (auto& p : ps) { std::cin >> p.first >> p.second; } auto cnt = vec(3, vec(n, 0LL)); for (int i = 0; i < 3; ++i) { for (int j = 0; j < n; ++j) { cnt[i][j] = std::count(ps[j].first.begin(), ps[j].first.end(), JOI[i]); } } std::vector dp(k * 3 + 1, INF); dp[0] = 0; for (int l = 0; l < k * 3; ++l) { if (l / k == (l + 100) / k) { for (int j = 0; j < n; ++j) { int r = l + cnt[l / k][j]; if (r > l) dp[r] = std::min(dp[r], dp[l] + ps[j].second); } } else { for (const auto& p : ps) { int r = l; for (char c : p.first) { if (c == JOI[r / k]) ++r; } if (r > l) dp[r] = std::min(dp[r], dp[l] + p.second); } } } auto ans = dp.back(); std::cout << (ans == INF ? -1 : ans) << std::endl; } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); solve(); return 0; }