#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1005;
int f1[N][N];
int f2[N][N];
int n,m;
int ans;
bool check=true;
int main(){
cin>>n>>m;
int pre;
int now;
int x,y;
while(n--){
cin>>now;
if(check) pre=now,check=false;
if(now!=pre) memcpy(f1, f2, sizeof f2);
cin>>x>>y;
f2[x][y]=max(max(f1[x-1][y],f1[x][y-1]),max(f1[x+1][y],f1[x][y+1]))+1;
pre=now;
ans=max(ans,f2[x][y]);
}
cout<<ans<<endl;
return 0;
}