N,K = map(int,input().split()) CS = [] for _ in range(N): s,c = input().split() CS.append([int(c),list(s)]) inf =10**18 DPJ = [inf]*(K+1) DPO = [inf]*(K+1) DPI = [inf]*(K+1) DPJ[0] = 0 for c,S in CS: cnt = S.count('J') if cnt==0: continue for i in range(K): if DPJ[i]!=inf: if i+cnt>=K: J=i O=0 I=0 for s in S: if J=K and s=='O': O+=1 if O>=K and s=='I': I+=1 if O>=K: DPI[min(K,I)]=min(DPJ[i]+c,DPI[min(K,I)]) elif J>=K: DPO[O]=min(DPJ[i]+c,DPO[O]) elif DPJ[i+cnt]>DPJ[i]+c: DPJ[i+cnt]=DPJ[i]+c for c,S in CS: cnt = S.count('O') if cnt==0: continue for i in range(K): if DPO[i]!=inf: if i+cnt>=K: O=i I=0 for s in S: if s=='O': O+=1 if O>=K and s=='I': I+=1 if O>=K: DPI[min(K,I)]=min(DPO[i]+c,DPI[min(K,I)]) elif DPO[i+cnt]>DPO[i]+c: DPO[i+cnt]=DPO[i]+c for c,S in CS: cnt = S.count('I') if cnt==0: continue for i in range(K): if DPI[i]!=inf: if DPI[min(K,i+cnt)]>DPI[i]+c: DPI[min(K,i+cnt)]=DPI[i]+c if DPI[-1]==inf: print(-1) else: print(DPI[-1])