import sys input = sys.stdin.readline N,M=map(int,input().split()) P=[list(map(int,input().split())) for i in range(N)] ANS=[0]*N TWO=0 THREE=0 LIST=[[] for i in range(10**5+2)] for i in range(N): ANS[i]=P[i][0] LIST[P[i][1]].append(i) for i in range(N): if ANS[i]>=2: TWO+=1 if ANS[i]>=3: THREE+=1 LANS=10**6 for i in range(10**5+1,-1,-1): for x in LIST[i]: ANS[x]+=1 if ANS[x]==3: THREE+=1 elif ANS[x]==2: TWO+=1 if TWO>=M: LANS=min(LANS,THREE) continue OK=0 NG=10**5+1 while NG>OK: mid=(OK+NG)//2 TWOX=TWO THREEX=THREE for i in range(N): k=P[i][2] if k>=mid: if ANS[i]+1==2: TWOX+=1 elif ANS[i]+1==3: THREEX+=1 if TWOX>=M: OK=mid else: NG=mid TWOX=TWO THREEX=THREE for i in range(N): k=P[i][2] if k>=OK: if ANS[i]+1==2: TWOX+=1 elif ANS[i]+1==3: THREEX+=1 LANS=min(LANS,THREEX) print(LANS)