#include using namespace std; using lint = long long int; struct fast_ios { fast_ios(){ cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; } fast_ios_; #define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i struct ShortestPath { int V, E; int INVALID = -1; std::vector>> to; ShortestPath() = default; ShortestPath(int V) : V(V), E(0), to(V) {} void add_edge(int s, int t, T len) { assert(0 <= s and s < V); assert(0 <= t and t < V); to[s].emplace_back(t, len); E++; } std::vector dist; std::vector prev; // Dijkstra algorithm // Complexity: O(E log E) void Dijkstra(int s) { assert(0 <= s and s < V); dist.assign(V, std::numeric_limits::max()); dist[s] = 0; prev.assign(V, INVALID); using P = std::pair; std::priority_queue, std::greater

> pq; pq.emplace(0, s); while(!pq.empty()) { T d; int v; std::tie(d, v) = pq.top(); pq.pop(); if (dist[v] < d) continue; for (auto nx : to[v]) { T dnx = d + nx.second; if (dist[nx.first] > dnx) { dist[nx.first] = dnx, prev[nx.first] = v; pq.emplace(dnx, nx.first); } } } } }; int main() { int N, K; cin >> N >> K; ShortestPath graph(K * 3 + 1); while (N--) { string S; lint C; cin >> S >> C; REP(i, K * 3) { int now = i; for (auto c : S) { if (now < K and c == 'J') now++; if (now >= K and now < K * 2 and c == 'O') now++; if (now >= K * 2 and now < K * 3 and c == 'I') now++; } graph.add_edge(i, now, C); } } graph.Dijkstra(0); cout << (graph.dist.back() > 4e18 ? -1 : graph.dist.back()) << '\n'; }