N,K=map(int,input().split()) S,C=[],[] J,O,I=[],[],[] for i in range(N): s,c=input().split() c=int(c) S.append(s) C.append(c) J.append(s.count("J")) O.append(s.count("O")) I.append(s.count("I")) JOI="J"*K+"O"*K+"I"*K inf=1<<60 dp=[inf]*(3*K+1) dp[0]=0 for k0 in range(3*K): for n in range(N): if K-k0%K>len(S[n]): if JOI[k0]=="J": k1=k0+J[n] elif JOI[k0]=="O": k1=k0+O[n] elif JOI[k0]=="I": k1=k0+I[n] else: k1=k0 for s in S[n]: if k1<3*K and JOI[k1]==s: k1+=1 dp[k1]=min(dp[k1],dp[k0]+C[n]) ans=dp[3*K] if ans==inf: ans=-1 print(ans)