N,M = map(int,input().split()) W = 10**5+10 X = [] C = [0,0,0,0,0,0] A = [[] for _ in range(W)] B = [[] for _ in range(W)] for n in range(N): x,a,b = map(int,input().split()) X.append(x+1) C[x+1] += 1 A[a].append(n) B[b].append(n) SA = 0; SB = W ans = W while True: if SA >= W: break if sum(C[2:])>=M and sum(C[3:]) 0 and sum(C[2:]) < M: SB -= 1 for b in B[SB]: C[X[b]] -= 1 X[b] += 1 C[X[b]] += 1 print(ans)