#include <iostream>
using namespace std;
int main()
{
int N;
int i, j;
int now[2]={0, 0};
int stop=0;
int ndec=4;
int next[2];
int wstop=0;
int m=0;
int nowg;
cin >> N;
int glass[N][2];
int dec[N];
for (i=0; i<N; i++)
{
cin >> glass[i][0] >> glass[i][1] >> dec[i];
}
while (stop == 0)
{
wstop = 1;
if (ndec == 1)
{
//cout << "1" << " m\n";
next[1] = 30001;
for (i=0; i<N; i++)
{
if (glass[i][0] == now[0])
{
next[0] = now[0];
if (glass[i][1] > now[1])
{
if (glass[i][1] <= next[1])
{
next[1] = glass[i][1];
nowg = i;
}
wstop = 0;
}
}
}
if (dec[nowg] == 0)
{
ndec = 4;
}
else
{
ndec = 3;
}
if (wstop == 1)
{
stop = 1;
}
else
{
now[1] = next[1];
m+=1;
}
}
else if (ndec == 2)
{
//cout << "2" << " m\n";
next[1] = -30001;
for (i=0; i<N; i++)
{
if (glass[i][0] == now[0])
{
//cout << i << " 1\n";
next[0] = now[0];
if (glass[i][1] < now[1])
{
//cout << i << " 2\n";
if (glass[i][1] >= next[1])
//cout << i << " 3\n";
next[1] = glass[i][1];
nowg = i;
wstop = 0;
}
}
}
if (dec[nowg] == 0)
{
ndec = 3;
}
else
{
ndec = 4;
}
if (wstop == 1)
{
stop = 1;
}
else
{
now[1] = next[1];
m+=1;
}
}
else if (ndec == 3)
{
//cout << "3" << " m\n";
next[0] = 0;
for (i=0; i<N; i++)
{
if (glass[i][1]== now[1])
{
next[1] = now[1];
if (glass[i][0] < now[0])
{
if (glass[i][0] >= next[0])
{
next[0] = glass[i][0];
nowg = i;
}
wstop = 0;
}
}
}
if (dec[nowg] == 0)
{
ndec = 2;
}
else
{
ndec = 1;
}
if (wstop == 1)
{
stop = 1;
}
else
{
now[0] = next[0];
m+=1;
}
}
else
{
//cout << "4" << " m\n";
next[0] = 30001;
for (i=0; i<N; i++)
{
if (glass[i][1]== now[1])
{
next[1] = now[1];
if (glass[i][0] > now[0])
{
if (glass[i][0] <= next[0])
{
next[0] = glass[i][0];
nowg = i;
}
wstop = 0;
}
}
}
if (dec[nowg] == 0)
{
ndec = 1;
}
else
{
ndec = 2;
}
if (wstop == 1)
{
stop = 1;
}
else
{
now[0] = next[0];
m+=1;
}
}
}
cout << m;
return 0;
}