local mmi, mma = math.min, math.max local mfl = math.floor local function comp(a, b) return a < b end local function lower_bound(ary, x) local num = #ary if num == 0 then return 1 end if not comp(ary[1], x) then return 1 end if comp(ary[num], x) then return num + 1 end local min, max = 1, num while 1 < max - min do local mid = mfl((min + max) / 2) if comp(ary[mid], x) then min = mid else max = mid end end return max end local n, k = io.read("*n", "*n", "*l") local w, len, c = {}, {}, {} for i = 1, n do local s = io.read() local wi, ci = s:match("(%w+) (%d+)") w[i] = wi len[i] = #wi c[i] = tonumber(ci) end local wj, wo, wi = {}, {}, {} for i = 1, n do wj[i] = {} local cj = 0 for j = 1, #w[i] do if w[i]:sub(j, j) == "J" then cj = cj + 1 end wj[i][j] = cj end wo[i] = {} local co = 0 for j = 1, #w[i] do if w[i]:sub(j, j) == "O" then co = co + 1 end wo[i][j] = co end wi[i] = {} local ci = 0 for j = 1, #w[i] do if w[i]:sub(j, j) == "I" then ci = ci + 1 end wi[i][j] = ci end end local t = {} local edge = {} for i = 1, k * 3 + 1 do edge[i] = {} t[i] = -1 end for i_n = 1, n do for j = 1, k * 3 do local step = 0 local need_j = mma(0, k + 1 - j) local need_o = mma(0, mmi(k, 2 * k + 1 - j)) local need_i = mmi(k, 3 * k + 1 - j) local offset = 0 if 0 < need_j then local pos = lower_bound(wj[i_n], need_j) if len[i_n] < pos then step = wj[i_n][len[i_n]] else step = need_j end offset = pos end if offset <= len[i_n] then if 0 < need_o then local ofst_o = offset == 0 and 0 or wo[i_n][offset] local pos = lower_bound(wo[i_n], need_o + ofst_o) if len[i_n] < pos then step = step + wo[i_n][len[i_n]] - ofst_o else step = step + need_o end offset = pos end end if offset <= len[i_n] then if 0 < need_i then local ofst_i = offset == 0 and 0 or wi[i_n][offset] local pos = lower_bound(wi[i_n], need_i + ofst_i) if len[i_n] < pos then step = step + wi[i_n][len[i_n]] - ofst_i else step = step + need_i end offset = pos end end if 0 < step then if edge[j][j + step] then edge[j][j + step] = mmi(edge[j][j + step], c[i_n]) else edge[j][j + step] = c[i_n] end end end--j end--i_n t[1] = 0 for i = 1, 3 * k do local srccost = t[i] if 0 <= srccost then for dst, cost in pairs(edge[i]) do if t[dst] == -1 then t[dst] = srccost + cost else t[dst] = mmi(t[dst], srccost + cost) end end end end print(t[3 * k + 1])