N,K=map(int,input().split()) S,C=[],[] for i in range(N): s,c=input().split() c=int(c) S.append(s) C.append(c) JOI="J"*K+"O"*K+"I"*K inf=1<<60 dp=[inf]*(3*K+1) dp[0]=0 for k0 in range(3*K+1): for n in range(N): 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)