import sys input = sys.stdin.readline N,K=map(int,input().split()) S=[input().split() for i in range(N)] DP=[1<<63]*(3*K+2+100) DP[0]=0 T=["J"]*K+["O"]*K+["I"]*K for i in range(3*K): #NEXT=T[i:i+80] for j in range(N): ind=0 M=int(S[j][1]) for s in S[j][0]: if i+ind<3*K and s==T[i+ind]: ind+=1 DP[i+ind]=min(DP[i+ind],DP[i]+M) if 1<<63==DP[K*3]: print(-1) else: print(DP[K*3])