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)] LIST2=[[] for i in range(10**5+2)] for i in range(N): ANS[i]=P[i][0] LIST[P[i][1]].append(i) LIST2[P[i][2]].append(i) for i in range(N): if ANS[i]>=2: TWO+=1 if ANS[i]>=3: THREE+=1 LANS=10**6 if TWO>=M: LANS=THREE SA=-1 SB=100001 for i in range(N): ANS[i]+=1 if ANS[i]==2: TWO+=1 if ANS[i]==3: THREE+=1 if TWO>=M: LANS=min(LANS,THREE) for SA in range(10**5+2): for x in LIST[SA]: ANS[x]-=1 if ANS[x]==2: THREE-=1 if ANS[x]==1: TWO-=1 while TWO0: SB-=1 for x in LIST2[SB]: ANS[x]+=1 if ANS[x]==2: TWO+=1 if ANS[x]==3: THREE+=1 if TWO>=M: LANS=min(LANS,THREE) print(LANS)