import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines N, K = map(int, readline().split()) S = [] C = [] for _ in range(N): x, y = readline().split() x = tuple(0 if x == 'J' else 1 if x == 'O' else 2 for x in x.decode()) S.append(x) C.append(int(y)) INF = 10 ** 16 dp = [INF] * (K + K + K + 1) dp[0] = 0 cnt = [0] * (N * 3) for q in range(3): for i in range(N): cnt[3 * i + q] = sum(n == q for n in S[i]) def solve_small(): def f(k, i): q, r = divmod(k, K) if k + cnt[3 * i + q] < K: return k + cnt[3 * i + q] for x in S[i]: if x == q: r += 1 if r == K: r = 0 q += 1 return K * q + r for k in range(K + K + K): for i in range(N): next_k = f(k, i) dp[next_k] = min(dp[k] + C[i], dp[next_k]) x = dp[-1] if x == INF: x = -1 return x if K <= 100: print(solve_small())