#include #include #include 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; } std::vector dp(k * 3 + 1, INF); dp[0] = 0; for (int l = 0; l < k * 3; ++l) { 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; }