#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } constexpr long long MAX = 5100000; constexpr long long INF = 1LL << 60; constexpr int inf = 1 << 28; constexpr long long mod = 1000000007LL; //constexpr long long mod = 998244353LL; using namespace std; typedef unsigned long long ull; typedef long long ll; int main() { /* cin.tie(nullptr); ios::sync_with_stdio(false); */ ll N, K; cin >> N >> K; vector vs(N); vector cost(N); for (int i = 0; i < N; i++) cin >> vs[i] >> cost[i]; vector> cnt(N, vector(3)); for (int i = 0; i < N; i++) { for (int j = 0; j < vs[i].size(); j++) { if (vs[i][j] == 'J') cnt[i][0]++; if (vs[i][j] == 'O') cnt[i][1]++; if (vs[i][j] == 'I') cnt[i][2]++; } } string t; t += string(K, 'J') + string(K, 'O') + string(K, 'I') + string(100, '#'); vector dp(3 * K + 500, INF); dp[0] = 0; for (int i = 0; i < 3 * K; i++) { for (int j = 0; j < N; j++) { int pos = i; if (t[i] == t[i + 80]) { pos += cnt[j][i / K]; } else { for (int k = 0; k < vs[j].size(); k++) { if (t[pos] == vs[j][k]) pos++; } } chmin(dp[pos], dp[i] + cost[j]); } } if (dp[3 * K] == INF) dp[3 * K] = -1; cout << dp[3 * K] << endl; return 0; }