#include <stdio.h>
#include <vector>
using namespace std;
int min(int a, int b){ return a>b?b:a;}
int max(int a, int b){ return a>b?a:b;}
int fun(int a, int b, int t)
{
	if(t==0) return min(a,b);
	return max(a,b);
}
const int N=100050;
const int M=4*N;
int x[M],ls[M],rs[M],clock,root[2][N];
void Set(int t, int &c, int ss, int se, int qi, int X)
{
	if(!c) c=++clock,x[c]=X;
	x[c]=fun(x[c],X,t);
	if(ss==se) return;
	int mid=ss+se>>1;
	if(qi<=mid) Set(t,ls[c],ss,mid,qi,X);
	else Set(t,rs[c],mid+1,se,qi,X);
}
int inf[2]={(int)1e9+7,-1};
int Get(int t, int c, int ss, int se, int qs, int qe)
{
	if(!c) return inf[t];
	if(ss>qe || qs>se) return inf[t];
	if(qs<=ss && qe>=se) return x[c];
	int mid=ss+se>>1;
	return fun(Get(t,ls[c],ss,mid,qs,qe),Get(t,rs[c],mid+1,se,qs,qe),t);
}
vector<int> Head;
int a[N],l[N],r[N],sz[N],par[N],type[N],CS[N],Index[N],Chain[N],time;
void DFS(int u)
{
	sz[u]=1;
	if(l[u]) DFS(l[u]),sz[u]+=sz[l[u]];
	if(r[u]) DFS(r[u]),sz[u]+=sz[r[u]];
}
void HLD(int u)
{
	if(!Chain[u])
	{
		Chain[u]=Head.size();
		Head.push_back(u);
		time=0;
	}
	Index[u]=++time;
	CS[Chain[u]]=time;
	int HC=0;
	if(l[u] && sz[l[u]]>sz[HC]) HC=l[u];
	if(r[u] && sz[r[u]]>sz[HC]) HC=r[u];
	if(HC)
	{
		Chain[HC]=Chain[u];
		HLD(HC);
		if(l[u] && HC!=l[u]) HLD(l[u]);
		if(r[u] && HC!=r[u]) HLD(r[u]);
	}
}
int main()
{
	Head.push_back(69);
	int n,i;
	scanf("%i",&n);
	for(i=1;i<=n;i++)
	{
		scanf("%i %i %i",&a[i],&l[i],&r[i]);
		if(l[i]==-1) l[i]=0;
		else par[l[i]]=i,type[l[i]]=0;
		if(r[i]==-1) r[i]=0;
		else par[r[i]]=i,type[r[i]]=1;
	}
	int r=0;
	for(i=1;i<=n;i++) if(!par[i]) r=i;
	DFS(r);
	HLD(r);
	for(i=1;i<=n;i++)
	{
		//printf("%i %i %i\n",i,Chain[i],Index[i]);
		if(!par[i]) continue;
		Set(type[i],root[type[i]][Chain[i]],1,CS[Chain[i]],Index[i],a[par[i]]);
	}
	int sol=0;
	//printf("%i %i\n",Get(0,root[0][1],1,CS[1],1,1),Get(1,root[1][1],1,CS[1],1,1));
	for(i=1;i<=n;i++)
	{
		int u=i;
		int Min=inf[0];
		int Max=inf[1];
		//printf(":D\n");
		while(u)
		{
			Min=min(Min,Get(0,root[0][Chain[u]],1,CS[Chain[u]],1,Index[u]));
			Max=max(Max,Get(1,root[1][Chain[u]],1,CS[Chain[u]],1,Index[u]));
			//printf("%i %i %i\n",u,Min,Max);
			u=par[Head[Chain[u]]];
		}
		//printf("%i %i %i\n",i,Min,Max);
		if(Min>a[i] && Max<a[i]) sol++;
	}
	printf("%i\n",n-sol);
	return 0;
}


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
typedef unsigned long long ULL;
typedef long long LL;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=3e6+7;
const double eps=0.00000001;
LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}

int n,m;
int i,ans,root;
bool isroot[maxn];
int v[maxn],l[maxn],r[maxn];
map<int,int> mp;
int solve(int x,int le,int ri){
	if (x==-1) return 0;
	int ret=0;
	if (le<=v[x]&&v[x]<=ri) ret+=mp[v[x]],mp[v[x]]=0;
	ret+=solve(l[x],le,min(ri,v[x]-1));
	ret+=solve(r[x],max(le,v[x]+1),ri);
	return ret;
}
int main()
{
	scanf("%d",&n);
	FOR(i,1,n){
		scanf("%d%d%d",&v[i],&l[i],&r[i]);
		if (l[i]!=-1) isroot[l[i]]=1;
		if (r[i]!=-1) isroot[r[i]]=1;
		mp[v[i]]++;
	}
	FOR(i,1,n) if (!isroot[i]) root=i;
	printf("%d",n-solve(root,0,1000000000));
}


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
typedef unsigned long long ULL;
typedef long long LL;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=3e6+7;
const double eps=0.00000001;
LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}

int n,m,root;
int i,ans;
bool isroot[maxn];
int v[maxn],l[maxn],r[maxn];
bool find(int x,int i){
	if (i==-1) return 1;
	if (v[i]==x) return 0;
	if (x<v[i]) return find(x,l[i]);
	else return find(x,r[i]);
}
int main()
{
	scanf("%d",&n);
	FOR(i,1,n){
		scanf("%d%d%d",&v[i],&l[i],&r[i]);
		isroot[l[i]]=isroot[r[i]]=1;
	}
	FOR(i,1,n) if (!isroot[i]) root=i;
	FOR(i,1,n){
		ans+=find(v[i],root);
	}
	printf("%d",ans);
}


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
typedef unsigned long long ULL;
typedef long long LL;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=3e6+7;
const double eps=0.00000001;
LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}

int n,m;
int i,ans;
bool isroot[maxn],root;
int v[maxn],l[maxn],r[maxn];
bool find(int x,int i){
	if (i==-1) return 1;
	if (v[i]==x) return 0;
	if (x<v[i]) return find(x,l[i]);
	else return find(x,r[i]);
}
int main()
{
	scanf("%d",&n);
	FOR(i,1,n){
		scanf("%d%d%d",&v[i],&l[i],&r[i]);
		isroot[l[i]]=isroot[r[i]]=1;
	}
	FOR(i,1,n) if (!isroot[i]) root=i;
	FOR(i,1,n){
		ans+=find(v[i],root);
	}
	printf("%d",ans);
}


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
typedef unsigned long long ULL;
typedef long long LL;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=3e6+7;
const double eps=0.00000001;
LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}

int n,m;
int i,ans,root;
bool isroot[maxn];
int v[maxn],l[maxn],r[maxn];
map<int,int> mp;
int solve(int x,int le,int ri){
	if (x==-1) return 0;
	int ret=0;
	if (le<=v[x]&&v[x]<=ri) ret+=mp[v[x]],mp[v[x]]=0;
	ret+=solve(l[x],le,min(ri,v[x]-1));
	ret+=solve(r[x],max(le,v[x]+1),ri);
	return ret;
}
int main()
{
	scanf("%d",&n);
	FOR(i,1,n){
		scanf("%d%d%d",&v[i],&l[i],&r[i]);
		isroot[l[i]]=isroot[r[i]]=1;
		mp[v[i]]++;
	}
	FOR(i,1,n) if (!isroot[i]) root=i;
	printf("%d",n-solve(root,0,100000000));
}


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
typedef unsigned long long ULL;
typedef long long LL;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=3e6+7;
const double eps=0.00000001;
LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}

int n,m;
int i,ans,root;
bool isroot[maxn];
int v[maxn],l[maxn],r[maxn];
bool find(int x,int i){
	if (i==-1) return 1;
	if (v[i]==x) return 0;
	if (x<v[i]) return find(x,l[i]);
	else return find(x,r[i]);
}
vector<int> V;
int main()
{
	scanf("%d",&n);
	FOR(i,1,n){
		scanf("%d%d%d",&v[i],&l[i],&r[i]);
		isroot[l[i]]=isroot[r[i]]=1;
		V.push_back(v[i]);
	}
	FOR(i,1,n) if (!isroot[i]) root=i;
//	sort(V.begin(),V.end()),V.erase(unique(V.begin(),V.end()),V.end());
	REP(i,V.size()){
		ans+=find(V[i],root);
	}
	printf("%d",ans);
}


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
typedef unsigned long long ULL;
typedef long long LL;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=3e6+7;
const double eps=0.00000001;
LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}

int n,m;
int i,ans,root;
bool isroot[maxn];
int v[maxn],l[maxn],r[maxn];
map<int,int> mp;
int solve(int x,int le,int ri){
	if (x==-1) return 0;
	int ret=0;
	if (le<=v[x]&&v[x]<=ri) ret+=mp[v[x]],mp[v[x]]=0;
	ret+=solve(l[x],le,min(ri,v[x]-1));
	ret+=solve(r[x],max(le,v[x]+1),ri);
	return ret;
}
int main()
{
	scanf("%d",&n);
	FOR(i,1,n){
		scanf("%d%d%d",&v[i],&l[i],&r[i]);
		if (l[i]!=-1) isroot[l[i]]=1;
		if (r[i]!=-1) isroot[r[i]]=1;
		mp[v[i]]++;
	}
	FOR(i,1,n) if (!isroot[i]) root=i;
	printf("%d",n-solve(root,0,100000000));
}


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
#define REP(I,N) for (I=0;I<N;I++)
#define rREP(I,N) for (I=N-1;I>=0;I--)
#define rep(I,S,N) for (I=S;I<N;I++)
#define rrep(I,S,N) for (I=N-1;I>=S;I--)
#define FOR(I,S,N) for (I=S;I<=N;I++)
typedef unsigned long long ULL;
typedef long long LL;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fll;
const LL M=1e9+7;
const LL maxn=3e6+7;
const double eps=0.00000001;
LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
template<typename T>inline T abs(T a) {return a>0?a:-a;}

int n,m;
int i,ans,root;
bool isroot[maxn];
int v[maxn],l[maxn],r[maxn];
bool find(int x,int i){
	if (i==-1) return 1;
	if (v[i]==x) return 0;
	if (x<v[i]) return find(x,l[i]);
	else return find(x,r[i]);
}
vector<int> V;
int main()
{
	scanf("%d",&n);
	FOR(i,1,n){
		scanf("%d%d%d",&v[i],&l[i],&r[i]);
		isroot[l[i]]=isroot[r[i]]=1;
		V.push_back(v[i]);
	}
	FOR(i,1,n) if (!isroot[i]) root=i;
	sort(V.begin(),V.end()),V.erase(unique(V.begin(),V.end()),V.end());
	REP(i,V.size()){
		ans+=find(V[i],root);
	}
	printf("%d",ans);
}


/* In the name of Allah */
#include <bits/stdc++.h>
using namespace std;

#define X first
#define Y second
#define pb push_back
#define mp make_pair
#define Size(x) ((int)(x).size())
#define Precision(i) cout << fixed << setprecision(i)

typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;

const int MAX_N = 1e5 + 10;
const int INF = 1e9 + 10;
int a[MAX_N], ans;
bool check[MAX_N];
int L[MAX_N], R[MAX_N];

void dfs(int u, int mn, int mx) {
	if(mn >= mx - 1)
		return;
	if(a[u] > mn && a[u] < mx)
		ans++;

	if(L[u] + 1)
		dfs(L[u], mn, min(mx, a[u]));
	if(R[u] + 1)
		dfs(R[u], max(mn, a[u]), mx);
}

int main() {
	ios_base :: sync_with_stdio(false), cin.tie(0), cout.tie(0);

	int n;
	cin >> n;
	set <int> s;
	for(int i = 0; i < n; i++)
		s.insert(i);

	for(int i = 0; i < n; i++) {
		cin >> a[i] >> L[i] >> R[i];

		if(L[i] + 1) {
			L[i]--;
			s.erase(L[i]);
		}
		if(R[i] + 1) {
			R[i]--;
			s.erase(R[i]);
		}
	}

	int root = *s.begin();
	s.clear();

	dfs(root, -INF, INF);
	cout << n - ans << endl;

	return 0;
}


/* In the name of Allah */
#include <bits/stdc++.h>
using namespace std;

#define X first
#define Y second
#define pb push_back
#define mp make_pair
#define Size(x) ((int)(x).size())
#define Precision(i) cout << fixed << setprecision(i)

typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;

const int MAX_N = 1e5 + 10;
const int INF = 1e9 + 10;
int a[MAX_N], ans;
bool check[MAX_N];
int L[MAX_N], R[MAX_N];

void dfs(int u, int mn, int mx) {
	if(a[u] > mn && a[u] < mx)
		ans++;

	if(L[u] + 1)
		dfs(L[u], mn, min(mx, a[u]));
	if(R[u] + 1)
		dfs(R[u], max(mn, a[u]), mx);
}

int main() {
	ios_base :: sync_with_stdio(false), cin.tie(0), cout.tie(0);

	int n;
	cin >> n;
	set <int> s;
	for(int i = 0; i < n; i++)
		s.insert(i);

	for(int i = 0; i < n; i++) {
		cin >> a[i] >> L[i] >> R[i];

		if(L[i] + 1) {
			L[i]--;
			s.erase(L[i]);
		}
		if(R[i] + 1) {
			R[i]--;
			s.erase(R[i]);
		}
	}

	int root = *s.begin();
	s.clear();

	dfs(root, -INF, INF);
	cout << n - ans << endl;

	return 0;
}


/* In the name of Allah */
#include <bits/stdc++.h>
using namespace std;

#define X first
#define Y second
#define pb push_back
#define mp make_pair
#define Size(x) ((int)(x).size())
#define Precision(i) cout << fixed << setprecision(i)

typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;

const int MAX_N = 1e5 + 10;
const int INF = 1e9 + 10;
int a[MAX_N];
int L[MAX_N], R[MAX_N];
set <int> s;

void dfs(int u, int mn, int mx) {
	if(a[u] >= mn && a[u] <= mx)
		s.erase(a[u]);

	if(L[u] + 1)
		dfs(L[u], mn, min(mx, a[u]));
	if(R[u] + 1)
		dfs(R[u], max(mn, a[u]), mx);
}

int main() {
	ios_base :: sync_with_stdio(false), cin.tie(0), cout.tie(0);

	int n;
	cin >> n;
	for(int i = 0; i < n; i++)
		s.insert(i);

	for(int i = 0; i < n; i++) {
		cin >> a[i] >> L[i] >> R[i];

		if(L[i] + 1) {
			L[i]--;
			s.erase(L[i]);
		}
		if(R[i] + 1) {
			R[i]--;
			s.erase(R[i]);
		}
	}

	int root = *s.begin();
	s.clear();

	for(int i = 0; i < n; i++)
		s.insert(a[i]);
	dfs(root, -INF, INF);
	cout << Size(s) << endl;

	return 0;
}


/* In the name of Allah */
#include <bits/stdc++.h>
using namespace std;

#define X first
#define Y second
#define pb push_back
#define mp make_pair
#define Size(x) ((int)(x).size())
#define Precision(i) cout << fixed << setprecision(i)

typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;

const int MAX_N = 1e5 + 10;
const int INF = 1e9 + 10;
int a[MAX_N];
map <int, int> x;
map <int, bool> check;
int L[MAX_N], R[MAX_N];

void dfs(int u, int mn, int mx) {
	if(mn > mx)
		return;
	if(a[u] >= mn && a[u] <= mx)
		check[a[u]] = true;

	if(L[u] + 1)
		dfs(L[u], mn, min(mx, a[u]));
	if(R[u] + 1)
		dfs(R[u], max(mn, a[u]), mx);
}

int main() {
	ios_base :: sync_with_stdio(false), cin.tie(0), cout.tie(0);

	int n;
	cin >> n;
	set <int> s;
	for(int i = 0; i < n; i++)
		s.insert(i);

	for(int i = 0; i < n; i++) {
		cin >> a[i] >> L[i] >> R[i];

		x[a[i]]++;
		if(L[i] + 1) {
			L[i]--;
			s.erase(L[i]);
		}
		if(R[i] + 1) {
			R[i]--;
			s.erase(R[i]);
		}
	}

	int root = *s.begin();
	dfs(root, -INF, INF);

	int ans = 0;
	for(int i = 0; i < n; i++)
		if(check[a[i]])
			check[a[i]] = false, ans += x[a[i]];
	cout << n - ans << endl;

	return 0;
}


/* In the name of Allah */
#include <bits/stdc++.h>
using namespace std;

#define X first
#define Y second
#define pb push_back
#define mp make_pair
#define Size(x) ((int)(x).size())
#define Precision(i) cout << fixed << setprecision(i)

typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;

const int MAX_N = 1e5 + 10;
const int INF = 1e9 + 10;
int a[MAX_N], ans;
bool check[MAX_N];
int L[MAX_N], R[MAX_N];

void dfs(int u, int mn, int mx) {
	if(a[u] >= mn && a[u] <= mx)
		ans++;

	if(L[u] + 1)
		dfs(L[u], mn, min(mx, a[u]));
	if(R[u] + 1)
		dfs(R[u], max(mn, a[u]), mx);
}

int main() {
	ios_base :: sync_with_stdio(false), cin.tie(0), cout.tie(0);

	int n;
	cin >> n;
	set <int> s;
	for(int i = 0; i < n; i++)
		s.insert(i);

	for(int i = 0; i < n; i++) {
		cin >> a[i] >> L[i] >> R[i];

		if(L[i] + 1) {
			L[i]--;
			s.erase(L[i]);
		}
		if(R[i] + 1) {
			R[i]--;
			s.erase(R[i]);
		}
	}

	int root = *s.begin();
	s.clear();

	dfs(root, -INF, INF);
	cout << n - ans << endl;

	return 0;
}


#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstring>
#include <iomanip>
#include <utility>
#include <iostream>
#include <algorithm>

using namespace std;
const int N = 1e5 + 5;
const int INF = 1e9 + 5;

int n, v[N];
int l[N], r[N];
bool par[N];
int root, ans;
set<int> found;

void dfs(int node, int mn, int mx) {
	if (mn > mx) return;
	if (mn <= v[node] && v[node] <= mx) found.insert(v[node]);
	if (l[node] != -1) dfs(l[node], mn, v[node] - 1);
	if (r[node] != -1) dfs(r[node], v[node] + 1, mx);
	return;
}

int main() {

	ios_base::sync_with_stdio(0);
	cin.tie(NULL);

	cin >> n;

	for (int i = 1; i <= n; i++) {
		cin >> v[i] >> l[i] >> r[i];
		if (l[i] != -1) par[l[i]] = true;
		if (r[i] != -1) par[r[i]] = true;
	}

	root = 1;
	while (par[root]) root++;

	dfs(root, 0, INF);

	for (int i = 1; i <= n; i++) {
		if (found.count(v[i])) ans++;
	}

	cout << n - ans << endl;

	return 0;
}


#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstring>
#include <iomanip>
#include <utility>
#include <iostream>
#include <algorithm>

using namespace std;
const int N = 1e5 + 5;
const int INF = 1e9 + 5;

int n, v[N];
int l[N], r[N];
bool par[N];
int root, ans;

void dfs(int node, int mn, int mx) {
	if (mn <= v[node] && v[node] <= mx) ans++;
	if (l[node] != -1) dfs(l[node], mn, v[node] - 1);
	if (r[node] != -1) dfs(r[node], v[node] + 1, mx);
	return;
}

int main() {

	ios_base::sync_with_stdio(0);
	cin.tie(NULL);

	cin >> n;

	for (int i = 1; i <= n; i++) {
		cin >> v[i] >> l[i] >> r[i];
		if (l[i] != -1) par[l[i]] = true;
		if (r[i] != -1) par[r[i]] = true;
	}

	root = 1;
	while (par[root]) root++;

	dfs(root, 0, INF);

	cout << n - ans << endl;

	return 0;
}


#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstring>
#include <iomanip>
#include <utility>
#include <iostream>
#include <algorithm>

using namespace std;
const int N = 1e5 + 5;
const int INF = 1e9 + 5;

int n, v[N];
int l[N], r[N];
bool par[N];
int root, ans;
set<int> found;

void dfs(int node, int mn, int mx) {
	if (mn > mx) return;
	if (mn <= v[node] && v[node] <= mx) found.insert(v[node]);
	if (l[node] != -1) dfs(l[node], mn, min(v[node] - 1, mx));
	if (r[node] != -1) dfs(r[node], max(v[node] + 1, mn), mx);
	return;
}

int main() {

	ios_base::sync_with_stdio(0);
	cin.tie(NULL);

	cin >> n;

	for (int i = 1; i <= n; i++) {
		cin >> v[i] >> l[i] >> r[i];
		if (l[i] != -1) par[l[i]] = true;
		if (r[i] != -1) par[r[i]] = true;
	}

	root = 1;
	while (par[root]) root++;

	dfs(root, -INF, INF);

	for (int i = 1; i <= n; i++) {
		if (found.count(v[i])) ans++;
	}

	cout << n - ans << endl;

	return 0;
}


#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstring>
#include <iomanip>
#include <utility>
#include <iostream>
#include <algorithm>

using namespace std;
const int N = 1e5 + 5;
const int INF = 1e9 + 5;

int n, v[N];
int l[N], r[N];
bool par[N];
int root, ans;
set<int> found;

void dfs(int node, int mn, int mx) {
	if (mn <= v[node] && v[node] <= mx) found.insert(v[node]);
	if (l[node] != -1) dfs(l[node], mn, v[node] - 1);
	if (r[node] != -1) dfs(r[node], v[node] + 1, mx);
	return;
}

int main() {

	ios_base::sync_with_stdio(0);
	cin.tie(NULL);

	cin >> n;

	for (int i = 1; i <= n; i++) {
		cin >> v[i] >> l[i] >> r[i];
		if (l[i] != -1) par[l[i]] = true;
		if (r[i] != -1) par[r[i]] = true;
	}

	root = 1;
	while (par[root]) root++;

	dfs(root, 0, INF);

	for (int i = 1; i <= n; i++) {
		if (found.count(v[i])) ans++;
	}

	cout << n - ans << endl;

	return 0;
}


#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstring>
#include <iomanip>
#include <utility>
#include <iostream>
#include <algorithm>

using namespace std;
const int N = 1e5 + 5;
const int INF = 1e9 + 5;

int n, v[N];
int l[N], r[N];
bool par[N];
int root, ans;

void dfs(int node, int mn, int mx) {
	if (mn > mx) return;
	if (mn <= v[node] && v[node] <= mx) ans++;
	if (l[node] != -1) dfs(l[node], mn, min(v[node] - 1, mx));
	if (r[node] != -1) dfs(r[node], max(v[node] + 1, mn), mx);
	return;
}

int main() {

	ios_base::sync_with_stdio(0);
	cin.tie(NULL);

	cin >> n;

	for (int i = 1; i <= n; i++) {
		cin >> v[i] >> l[i] >> r[i];
		if (l[i] != -1) par[l[i]] = true;
		if (r[i] != -1) par[r[i]] = true;
	}

	root = 1;
	while (par[root]) root++;

	dfs(root, -INF, INF);

	cout << n - ans << endl;

	return 0;
}


#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstring>
#include <iomanip>
#include <utility>
#include <iostream>
#include <algorithm>

using namespace std;
const int N = 1e5 + 5;
const int INF = 1e9 + 5;

int n, v[N];
int l[N], r[N];
bool par[N];
int root, ans;
set<int> found;

void dfs(int node, int mn, int mx) {
	if (mn > mx) return;
	if (mn <= v[node] && v[node] <= mx) /*found.insert(v[node])*/ans++;
	if (l[node] != -1) dfs(l[node], mn, v[node] - 1);
	if (r[node] != -1) dfs(r[node], v[node] + 1, mx);
	return;
}

int main() {

	ios_base::sync_with_stdio(0);
	cin.tie(NULL);

	cin >> n;

	for (int i = 1; i <= n; i++) {
		cin >> v[i] >> l[i] >> r[i];
		if (l[i] != -1) par[l[i]] = true;
		if (r[i] != -1) par[r[i]] = true;
	}

	root = 1;
	while (par[root]) root++;

	dfs(root, 0, INF);

	/*for (int i = 1; i <= n; i++) {
		if (found.count(v[i])) ans++;
	}*/

	cout << n - ans << endl;

	return 0;
}


#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstring>
#include <iomanip>
#include <utility>
#include <iostream>
#include <algorithm>

using namespace std;
const int N = 1e5 + 5;
const int INF = 1e9 + 5;

int n, v[N];
int l[N], r[N];
bool par[N];
int root, ans;

void dfs(int node, int mn, int mx) {
	if (mn > mx) return;
	if (mn <= v[node] && v[node] <= mx) ans++;
	if (l[node] != -1) dfs(l[node], mn, min(v[node] - 1, mx));
	if (r[node] != -1) dfs(r[node], max(v[node] + 1, mn), mx);
	return;
}

int main() {

	ios_base::sync_with_stdio(0);
	cin.tie(NULL);

	cin >> n;

	for (int i = 1; i <= n; i++) {
		cin >> v[i] >> l[i] >> r[i];
		if (l[i] != -1) par[l[i]] = true;
		if (r[i] != -1) par[r[i]] = true;
	}

	root = 1;
	while (par[root]) root++;

	dfs(root, 0, INF);

	cout << n - ans << endl;

	return 0;
}


#include<bits/stdc++.h>
#include<time.h>
#include<stdlib.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse4")
#define pb push_back
#define mp make_pair
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define pll pair<ll,ll>
#define vll vector<ll,ll>
#define all(a) (a).begin(),(a).end()
#define ff first
#define ss second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define repf(i,a,b) for(ll i=a;i<b;i++)
#define repb(i,a,b) for(ll i=a;i>b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define gcd(a,b) __gcd((a),(b))
#define EPS 1e-12
#define lcm(a,b) ((a)*(b))/__gcd((a),(b))
#define sqrt sqrtl
#define cbrt cbrtl
using namespace std;
struct node
{
	ll data;
	struct node *left,*right;
};
ll c,mini=1e18,maxi=-1e18,p[100005],l[100005],r[100005],val[100005];
node *root=NULL;
struct node* insert(ll ind)
{
	struct node* newnode=(struct node*)malloc(sizeof(struct node));
	newnode->data=val[ind];
	newnode->left=NULL;
	newnode->right=NULL;
	if(l[ind]!=-1)
		newnode->left=insert(l[ind]);
	if(r[ind]!=-1)
		newnode->right=insert(r[ind]);
	return newnode;
}
void check(struct node* root,ll mn,ll mx)
{
	if(root->data>=mn && root->data<=mx)
		{
			//cout<<root->data<<" ";
			c++;
		}
	if(root->left)
	{
				check(root->left,mn,min(mx,root->data));

	}
	if(root->right)
	{
			check(root->right,max(mn,root->data),mx);
	}
}
int32_t main()
{
	IOS
	ll n,i,j;
	cin>>n;
	for(i=1;i<=n;i++)
		{
			cin>>val[i]>>l[i]>>r[i];
			mini=min(mini,val[i]);
			if(l[i]!=-1)
				p[l[i]]=1;
			if(r[i]!=-1)
				p[r[i]]=1;
		}
	for(i=1;i<=n;i++)
		if(p[i]==0)
			break;
		ll head=i;
		root=insert(i);
		//cout<<val[head]<<"\n";
		check(root,-1e18,1e18);
		cout<<n-c;
	return 0;
}


#include<bits/stdc++.h>
#include<time.h>
#include<stdlib.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse4")
#define pb push_back
#define mp make_pair
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define pll pair<ll,ll>
#define vll vector<ll,ll>
#define all(a) (a).begin(),(a).end()
#define ff first
#define ss second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define repf(i,a,b) for(ll i=a;i<b;i++)
#define repb(i,a,b) for(ll i=a;i>b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define gcd(a,b) __gcd((a),(b))
#define EPS 1e-12
#define lcm(a,b) ((a)*(b))/__gcd((a),(b))
#define sqrt sqrtl
#define cbrt cbrtl
using namespace std;
map<ll,ll> mpp;
struct node
{
	ll data;
	struct node *left,*right;
};
ll c,mini=1e18,maxi=-1e18,p[100005],l[100005],r[100005],val[100005];
node *root=NULL;
struct node* insert(ll ind)
{
	struct node* newnode=(struct node*)malloc(sizeof(struct node));
	newnode->data=val[ind];
	newnode->left=NULL;
	newnode->right=NULL;
	if(l[ind]!=-1)
		newnode->left=insert(l[ind]);
	if(r[ind]!=-1)
		newnode->right=insert(r[ind]);
	return newnode;
}
void check(struct node* root,ll mn,ll mx)
{
	if(root->data>=mn && root->data<=mx)
		{
				c++;
		}
	if(root->left)
	{
				check(root->left,mn,min(mx,root->data)-1);

	}
	if(root->right)
	{
			check(root->right,max(mn,root->data),mx);
	}
}
int32_t main()
{
	IOS
	ll n,i,j;
	cin>>n;
	set<ll> s;
	for(i=1;i<=n;i++)
		{
			cin>>val[i]>>l[i]>>r[i];
			s.insert(val[i]);
			mini=min(mini,val[i]);
			if(l[i]!=-1)
				p[l[i]]=1;
			if(r[i]!=-1)
				p[r[i]]=1;
		}
	for(i=1;i<=n;i++)
		if(p[i]==0)
			break;
		ll head=i;
		root=insert(i);
		//cout<<val[head]<<"\n";
		check(root,-1e18,1e18);
		cout<<max(0LL,s.size()-c);
	return 0;
}


#include<bits/stdc++.h>
#include<time.h>
#include<stdlib.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse4")
#define pb push_back
#define mp make_pair
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define pll pair<ll,ll>
#define vll vector<ll,ll>
#define all(a) (a).begin(),(a).end()
#define ff first
#define ss second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define repf(i,a,b) for(ll i=a;i<b;i++)
#define repb(i,a,b) for(ll i=a;i>b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define gcd(a,b) __gcd((a),(b))
#define EPS 1e-12
#define lcm(a,b) ((a)*(b))/__gcd((a),(b))
#define sqrt sqrtl
#define cbrt cbrtl
using namespace std;
struct node
{
	ll data;
	struct node *left,*right;
};
ll p[100005],l[100005],r[100005],val[100005];
node *root=NULL;
struct node* insert(ll ind)
{
	struct node* newnode=(struct node*)malloc(sizeof(struct node));
	newnode->data=val[ind];
	newnode->left=NULL;
	newnode->right=NULL;
	if(l[ind]!=-1)
		newnode->left=insert(l[ind]);
	if(r[ind]!=-1)
		newnode->right=insert(r[ind]);
	return newnode;

}
vector<ll> ans;
void inorder(struct node* root)
{
	if(!root)
		return ;
	inorder(root->left);
	ans.pb(root->data);
	inorder(root->right);
}
int32_t main()
{
	IOS
	ll n,i,j;
	cin>>n;
	for(i=1;i<=n;i++)
		{
			cin>>val[i]>>l[i]>>r[i];
			if(l[i]!=-1)
				p[l[i]]=1;
			if(r[i]!=-1)
				p[r[i]]=1;
		}
	for(i=1;i<=n;i++)
		if(p[i]==0)
			break;
		ll head=i;
		root=insert(i);
		inorder(root);
		for(i=0;i<ans.size();i++)
			if(ans[i]==head)
				break;
			ll c=1;
			ll prev=head;
			for(j=i-1;j>=0;j--)
				if(ans[j]<prev)
				{
					prev=ans[j];
					c++;
				}
			prev=head;
			for(j=i+1;j<ans.size();j++)
				if(ans[j]>prev)
				{
					prev=ans[j];
					c++;
				}
				cout<<n-c;
	return 0;
}


#include<bits/stdc++.h>
#include<time.h>
#include<stdlib.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse4")
#define pb push_back
#define mp make_pair
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define pll pair<ll,ll>
#define vll vector<ll,ll>
#define all(a) (a).begin(),(a).end()
#define ff first
#define ss second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define repf(i,a,b) for(ll i=a;i<b;i++)
#define repb(i,a,b) for(ll i=a;i>b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define gcd(a,b) __gcd((a),(b))
#define EPS 1e-12
#define lcm(a,b) ((a)*(b))/__gcd((a),(b))
#define sqrt sqrtl
#define cbrt cbrtl
using namespace std;
struct node
{
	ll data;
	struct node *left,*right;
};
ll p[100005],l[100005],r[100005],val[100005];
node *root=NULL;
struct node* insert(ll ind)
{
	struct node* newnode=(struct node*)malloc(sizeof(struct node));
	newnode->data=val[ind];
	newnode->left=NULL;
	newnode->right=NULL;
	if(l[ind]!=-1)
		newnode->left=insert(l[ind]);
	if(r[ind]!=-1)
		newnode->right=insert(r[ind]);
	return newnode;

}
vector<ll> ans;
void inorder(struct node* root)
{
	if(!root)
		return ;
	inorder(root->left);
	ans.pb(root->data);
	inorder(root->right);
}
int32_t main()
{
	IOS
	ll n,i,j;
	cin>>n;
	ll mini=1e18;
	for(i=1;i<=n;i++)
		{
			cin>>val[i]>>l[i]>>r[i];
			mini=min(mini,val[i]);
			if(l[i]!=-1)
				p[l[i]]=1;
			if(r[i]!=-1)
				p[r[i]]=1;
		}
	for(i=1;i<=n;i++)
		if(p[i]==0)
			break;
		ll head=i;
		root=insert(i);
		inorder(root);
		for(i=0;i<ans.size();i++)
			if(ans[i]==val[head])
				break;
			ll c=1;
			ll prev=val[head];
			for(j=i-1;j>=0;j--)
				if(ans[j]<prev)
				{
					prev=ans[j];
					c++;
				}
			prev=val[head];
			for(j=i+1;j<ans.size();j++)
				if(ans[j]>prev)
				{
					prev=ans[j];
					c++;
				}
				cout<<n-c;
	return 0;
}


#include<bits/stdc++.h>
#include<time.h>
#include<stdlib.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse4")
#define pb push_back
#define mp make_pair
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define pll pair<ll,ll>
#define vll vector<ll,ll>
#define all(a) (a).begin(),(a).end()
#define ff first
#define ss second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define repf(i,a,b) for(ll i=a;i<b;i++)
#define repb(i,a,b) for(ll i=a;i>b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define gcd(a,b) __gcd((a),(b))
#define EPS 1e-12
#define lcm(a,b) ((a)*(b))/__gcd((a),(b))
#define sqrt sqrtl
#define cbrt cbrtl
using namespace std;
map<ll,ll> mpp;
struct node
{
	ll data;
	struct node *left,*right;
};
ll c,mini=1e18,maxi=-1e18,p[100005],l[100005],r[100005],val[100005];
node *root=NULL;
struct node* insert(ll ind)
{
	struct node* newnode=(struct node*)malloc(sizeof(struct node));
	newnode->data=val[ind];
	newnode->left=NULL;
	newnode->right=NULL;
	if(l[ind]!=-1)
		newnode->left=insert(l[ind]);
	if(r[ind]!=-1)
		newnode->right=insert(r[ind]);
	return newnode;
}
void check(struct node* root,ll mn,ll mx)
{
	if(root->data>=mn && root->data<=mx)
		{
			if(!mpp[root->data])
			{
				c++;
				mpp[root->data]=1;
			}
		}
	if(root->left)
	{
				check(root->left,mn,min(mx,root->data));

	}
	if(root->right)
	{
			check(root->right,max(mn,root->data),mx);
	}
}
int32_t main()
{
	IOS
	ll n,i,j;
	cin>>n;
	set<ll> s;
	for(i=1;i<=n;i++)
		{
			cin>>val[i]>>l[i]>>r[i];
			s.insert(val[i]);
			mini=min(mini,val[i]);
			if(l[i]!=-1)
				p[l[i]]=1;
			if(r[i]!=-1)
				p[r[i]]=1;
		}
	for(i=1;i<=n;i++)
		if(p[i]==0)
			break;
		ll head=i;
		root=insert(i);
		//cout<<val[head]<<"\n";
		check(root,-1e18,1e18);
		cout<<s.size()-c;
	return 0;
}


#include<bits/stdc++.h>
#include<time.h>
#include<stdlib.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse4")
#define pb push_back
#define mp make_pair
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define pll pair<ll,ll>
#define vll vector<ll,ll>
#define all(a) (a).begin(),(a).end()
#define ff first
#define ss second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define repf(i,a,b) for(ll i=a;i<b;i++)
#define repb(i,a,b) for(ll i=a;i>b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define gcd(a,b) __gcd((a),(b))
#define EPS 1e-12
#define lcm(a,b) ((a)*(b))/__gcd((a),(b))
#define sqrt sqrtl
#define cbrt cbrtl
using namespace std;
map<ll,ll> mpp;
struct node
{
	ll data;
	struct node *left,*right;
};
ll c,mini=1e18,maxi=-1e18,p[100005],l[100005],r[100005],val[100005];
node *root=NULL;
struct node* insert(ll ind)
{
	struct node* newnode=(struct node*)malloc(sizeof(struct node));
	newnode->data=val[ind];
	newnode->left=NULL;
	newnode->right=NULL;
	if(l[ind]!=-1)
		newnode->left=insert(l[ind]);
	if(r[ind]!=-1)
		newnode->right=insert(r[ind]);
	return newnode;
}
void check(struct node* root,ll mn,ll mx)
{
	if(root->data>=mn && root->data<=mx)
		{
			//cout<<root->data<<" ";
			if(mpp[root->data]==1)
			{
				c--;
				mpp[root->data]=0;
			}
		}
	if(root->left)
	{
				check(root->left,mn,min(mx,root->data));

	}
	if(root->right)
	{
			check(root->right,max(mn,root->data),mx);
	}
}
int32_t main()
{
	IOS
	ll n,i,j;
	cin>>n;
	for(i=1;i<=n;i++)
		{
			cin>>val[i]>>l[i]>>r[i];
			if(mpp[val[i]]==0)
			{
				mpp[val[i]]=1;
				c++;
			}
			mini=min(mini,val[i]);
			if(l[i]!=-1)
				p[l[i]]=1;
			if(r[i]!=-1)
				p[r[i]]=1;
		}
	for(i=1;i<=n;i++)
		if(p[i]==0)
			break;
		ll head=i;
		root=insert(i);
		//cout<<val[head]<<"\n";
		check(root,-1e18,1e18);
		cout<<c;
	return 0;
}


#include<bits/stdc++.h>
#include<time.h>
#include<stdlib.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse4")
#define pb push_back
#define mp make_pair
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define pll pair<ll,ll>
#define vll vector<ll,ll>
#define all(a) (a).begin(),(a).end()
#define ff first
#define ss second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define repf(i,a,b) for(ll i=a;i<b;i++)
#define repb(i,a,b) for(ll i=a;i>b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define gcd(a,b) __gcd((a),(b))
#define EPS 1e-12
#define lcm(a,b) ((a)*(b))/__gcd((a),(b))
#define sqrt sqrtl
#define cbrt cbrtl
using namespace std;
set<ll> s;
struct node
{
	ll data;
	struct node *left,*right;
};
ll c,mini=1e18,maxi=-1e18,p[100005],l[100005],r[100005],val[100005];
node *root=NULL;
struct node* insert(ll ind)
{
	struct node* newnode=(struct node*)malloc(sizeof(struct node));
	newnode->data=val[ind];
	newnode->left=NULL;
	newnode->right=NULL;
	if(l[ind]!=-1)
		newnode->left=insert(l[ind]);
	if(r[ind]!=-1)
		newnode->right=insert(r[ind]);
	return newnode;
}
void check(struct node* root,ll mn,ll mx)
{
	if(root->data>mn && root->data<mx)
		{
			s.insert(root->data);
		}
	if(root->left)
	{
				check(root->left,mn,min(mx,root->data));

	}
	if(root->right)
	{
			check(root->right,max(mn,root->data),mx);
	}
}
int32_t main()
{
	IOS
	ll n,i,j;
	cin>>n;
	for(i=1;i<=n;i++)
		{
			cin>>val[i]>>l[i]>>r[i];
			mini=min(mini,val[i]);
			if(l[i]!=-1)
				p[l[i]]=1;
			if(r[i]!=-1)
				p[r[i]]=1;
		}
	for(i=1;i<=n;i++)
		if(p[i]==0)
			break;
		ll head=i;
		root=insert(i);
		//cout<<val[head]<<"\n";
		check(root,-1e18,1e18);
		ll ans=0;
		for(i=1;i<=n;i++)
			ans+=s.count(val[i]);
		cout<<n-ans;
	return 0;
}


#include<bits/stdc++.h>
#include<time.h>
#include<stdlib.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse4")
#define pb push_back
#define mp make_pair
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define pll pair<ll,ll>
#define vll vector<ll,ll>
#define all(a) (a).begin(),(a).end()
#define ff first
#define ss second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define repf(i,a,b) for(ll i=a;i<b;i++)
#define repb(i,a,b) for(ll i=a;i>b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define gcd(a,b) __gcd((a),(b))
#define EPS 1e-12
#define lcm(a,b) ((a)*(b))/__gcd((a),(b))
#define sqrt sqrtl
#define cbrt cbrtl
using namespace std;
struct node
{
	ll data;
	struct node *left,*right;
};
ll c,mini=1e18,maxi=-1e18,p[100005],l[100005],r[100005],val[100005];
node *root=NULL;
struct node* insert(ll ind)
{
	struct node* newnode=(struct node*)malloc(sizeof(struct node));
	newnode->data=val[ind];
	newnode->left=NULL;
	newnode->right=NULL;
	if(l[ind]!=-1)
		newnode->left=insert(l[ind]);
	if(r[ind]!=-1)
		newnode->right=insert(r[ind]);
	return newnode;
}
void check(struct node* root,ll mn,ll mx)
{
	if(root->data>=mn && root->data<=mx)
		{
			//cout<<root->data<<" ";
			c++;
		}
	else
		return;

	if(root->left)
	{
				check(root->left,mn,root->data);

	}
	if(root->right)
	{
			check(root->right,root->data,mx);
	}
}
int32_t main()
{
	IOS
	ll n,i,j;
	cin>>n;
	for(i=1;i<=n;i++)
		{
			cin>>val[i]>>l[i]>>r[i];
			mini=min(mini,val[i]);
			if(l[i]!=-1)
				p[l[i]]=1;
			if(r[i]!=-1)
				p[r[i]]=1;
		}
	for(i=1;i<=n;i++)
		if(p[i]==0)
			break;
		ll head=i;
		root=insert(i);
		check(root,-1e18,1e18);
		cout<<n-c;
	return 0;
}


#include<bits/stdc++.h>
#include<time.h>
#include<stdlib.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse4")
#define pb push_back
#define mp make_pair
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define pll pair<ll,ll>
#define vll vector<ll,ll>
#define all(a) (a).begin(),(a).end()
#define ff first
#define ss second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define repf(i,a,b) for(ll i=a;i<b;i++)
#define repb(i,a,b) for(ll i=a;i>b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define gcd(a,b) __gcd((a),(b))
#define EPS 1e-12
#define lcm(a,b) ((a)*(b))/__gcd((a),(b))
#define sqrt sqrtl
#define cbrt cbrtl
using namespace std;
map<ll,ll> mpp;
struct node
{
	ll data;
	struct node *left,*right;
};
ll c,mini=1e18,maxi=-1e18,p[100005],l[100005],r[100005],val[100005];
node *root=NULL;
struct node* insert(ll ind)
{
	struct node* newnode=(struct node*)malloc(sizeof(struct node));
	newnode->data=val[ind];
	newnode->left=NULL;
	newnode->right=NULL;
	if(l[ind]!=-1)
		newnode->left=insert(l[ind]);
	if(r[ind]!=-1)
		newnode->right=insert(r[ind]);
	return newnode;
}
void check(struct node* root,ll mn,ll mx)
{
	if(root->data>mn && root->data<mx)
		{
			//cout<<root->data<<" ";
			if(mpp[root->data]==1)
			{
				c--;
				mpp[root->data]=0;
			}
		}
	if(root->left)
	{
				check(root->left,mn,min(mx,root->data));

	}
	if(root->right)
	{
			check(root->right,max(mn,root->data),mx);
	}
}
int32_t main()
{
	IOS
	ll n,i,j;
	cin>>n;
	for(i=1;i<=n;i++)
		{
			cin>>val[i]>>l[i]>>r[i];
			if(mpp[val[i]]==0)
			{
				mpp[val[i]]=1;
				c++;
			}
			mini=min(mini,val[i]);
			if(l[i]!=-1)
				p[l[i]]=1;
			if(r[i]!=-1)
				p[r[i]]=1;
		}
	for(i=1;i<=n;i++)
		if(p[i]==0)
			break;
		ll head=i;
		root=insert(i);
		//cout<<val[head]<<"\n";
		check(root,-1e18,1e18);
		cout<<c;
	return 0;
}


#include<bits/stdc++.h>
#include<time.h>
#include<stdlib.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse4")
#define pb push_back
#define mp make_pair
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define pll pair<ll,ll>
#define vll vector<ll,ll>
#define all(a) (a).begin(),(a).end()
#define ff first
#define ss second
#define sz(x) (ll)x.size()
#define hell 1000000007
#define repf(i,a,b) for(ll i=a;i<b;i++)
#define repb(i,a,b) for(ll i=a;i>b;i--)
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define gcd(a,b) __gcd((a),(b))
#define EPS 1e-12
#define lcm(a,b) ((a)*(b))/__gcd((a),(b))
#define sqrt sqrtl
#define cbrt cbrtl
using namespace std;
map<ll,ll> mpp;
struct node
{
	ll data;
	struct node *left,*right;
};
ll c,mini=1e18,maxi=-1e18,p[100005],l[100005],r[100005],val[100005];
node *root=NULL;
struct node* insert(ll ind)
{
	struct node* newnode=(struct node*)malloc(sizeof(struct node));
	newnode->data=val[ind];
	newnode->left=NULL;
	newnode->right=NULL;
	if(l[ind]!=-1)
		newnode->left=insert(l[ind]);
	if(r[ind]!=-1)
		newnode->right=insert(r[ind]);
	return newnode;
}
void check(struct node* root,ll mn,ll mx)
{
	if(root->data>=mn && root->data<=mx)
		{
				c++;
		}
	if(root->left)
	{
				check(root->left,mn,min(mx,root->data));

	}
	if(root->right)
	{
			check(root->right,max(mn,root->data),mx);
	}
}
int32_t main()
{
	IOS
	ll n,i,j;
	cin>>n;
	set<ll> s;
	for(i=1;i<=n;i++)
		{
			cin>>val[i]>>l[i]>>r[i];
			s.insert(val[i]);
			mini=min(mini,val[i]);
			if(l[i]!=-1)
				p[l[i]]=1;
			if(r[i]!=-1)
				p[r[i]]=1;
		}
	for(i=1;i<=n;i++)
		if(p[i]==0)
			break;
		ll head=i;
		root=insert(i);
		//cout<<val[head]<<"\n";
		check(root,-1e18,1e18);
		cout<<max(0LL,(ll)s.size()-c);
	return 0;
}


a=list(input())
b=[]
for i in set(a):
    b.append(a.count(i))
print(sum(i**2 for i in b))


a=list(input())
print(sum(a.count(i)**2 for i in set(a)))


import math

def main():
    s = input()

    d = {}
    for c in s:
        if(c not in d):
            d[c] = 1
        else:
            d[c] += 1

    ans = 0
    for a, b in d.items():
        ans += b * b

    print(ans)

main()


s = input()

counts = [s.count(x) for x in set(s)]

print(sum(map(lambda x: x*x, counts)))


s = str(input())
l = list(s)
l.sort()
counter1 = 0
counter2 = 0
ans = 0
tmp = l[0]
while(counter1 < len(l)):
    tmp = l[counter1]
    counter2 = counter1
    while(counter2 < len(l) and l[counter2] == tmp):
        counter2 += 1
    x = (counter2 - counter1) ** 2
    ans += x
    counter1 = counter2
print(ans)


a = str(input())
b = 0
for i in range(len(a)):
    for k in range(len(a)):
        if a[i] == a[k]:
            b += 1
print(b)


s = input()
chr_num = {}
for i in s:
    chr_num[i] = 0
for i in s:
    chr_num[i] += 1
ans = 0
for i in chr_num.values():
    ans += i**2
print(ans)


'''
Nome: Ivan Rosa Soares Júnior
Matricula: 2015083590
Solução: Contar o numero de vezes que cada letra aparece e imprimir a soma do
quadrado de cada um desses números.
'''

from collections import Counter as C
print(sum(v**2 for v in C(input().strip()).values()))


'''
Nome: Ivan Rosa Soares Júnior
Matricula: 2015083590
Solução: Contar o numero de vezes que cada letra aparece e imprimir a soma do
quadrado de cada um desses números.
'''

from itertools import Count as C
sum(v**2 for v in C(input().strip()).values())


s = input()
se = set(s)
res = 0

for i in se:
  res += (s.count(i))**2
print(res)


x = input()
dictx = {}
for i in x:
    if i in dictx:
        dictx[i] += 1
    else:
        dictx[i] = 1

total = 0
for i in dictx:
    total += (dictx[i])**2
print(total)


from math import pow

string = input()
contadores = {}
total = 0

for simbolo in string:
    contadores.setdefault(simbolo, 0)
    contadores[simbolo] += 1

for simbolo in string:
    total += pow(contadores[simbolo], 2)

print(int(total))


from math import pow

string = input()
contadores = {}
total = 0

for simbolo in string:
    contadores.setdefault(simbolo, 0)
    contadores[simbolo] += 1

for simbolo in contadores:
    total += contadores[simbolo] ** 2

print(int(total))


s = input()
from collections import Counter
cnts = Counter(s)
cnt = 0
for i in s:
	cnt += (cnts[i])
print(cnt)


a = input()

fq = []
sol = 0
for i in range(1, 200):
        fq.append(0)

for i in a:
        fq[ord(i)] += 1

for i in a:
        if fq[ord(i)] != 0:
                sol += (fq[ord(i)] - 1)

sol += len(a)

print(sol)


s=str(input())
k=len(s)
if s==s[0]*len(s):
    k=(len(s))*(len(s))
else:
    for i in range(len(s)):
        for j in range(len(s)):
            if j==i:
                pass
            elif s[i]==s[j]:
                k+=1
print(k)


s=str(input())
k=0
for i in range(len(s)):
    for j in range(len(s)):
        if s[i]==s[j]:
            k+=1
print(k)


s=str(input())
k=1
arr=[]
res=0
test='qwertyuiopasdfghjklzxcvbnm0123456789'
for i in range(len(s)):
    arr.append(s[i])
arr.sort()
fl=True
i=0
while i <(len(arr)-1) and fl:
    if arr[i+1]==arr[i]:
        k+=1
    else:
        res=res+(k*k)
        k=1
    if i==len(arr)-2:
        fl=False
    if fl==False:
        res=res+(k*k)
    i+=1
if i==0:
    res=1
print(res)


s=str(input())
k=1
arr=[]
res=0
test='qwertyuiopasdfghjklzxcvbnm0123456789'
for i in range(len(s)):
    arr.append(s[i])
arr.sort()
fl=True
i=0
while i <(len(arr)-1) and fl:
    if arr[i+1]==arr[i]:
        k+=1
    else:
        res=res+(k*k)
        k=1
    if i==len(arr)-2:
        fl=False
    if fl==False:
        res=res+(k*k)
    i+=1
print(res)


s=str(input())
k=len(s)
if s==s[0]*len(s):
    k=(len(s)+1)*(len(s)+1)
else:
    for i in range(len(s)):
        for j in range(len(s)):
            if j==i:
                pass
            elif s[i]==s[j]:
                k+=1
print(k)


s=str(input())
a=set(s)
l=list(s)
res=0
for i in range(len(a)):
    res+=l.count(a[i])
print(res)


s=str(input())
k=len(s)
for i in range(len(s)):
    for j in range(len(s)):
        if j==i:
            pass
        elif s[i]==s[j]:
            k+=1
print(k)


a=list(input());s=0
for i in set(a):
    s+=(a.count(i))**2
print(s)


# Codeforces 50B
s = input()
print(sum([list(s).count(i) for i in s]))


# Codeforces 50B
s = input()
#print(sum([list(s).count(i) for i in s]))
counted = []
count = 0
for i in s:
    if i not in counted:
        counted.append(i)
        count += list(s).count(i)**2
print(count)


# Codeforces 50B
s = input()
#print(sum([list(s).count(i) for i in s]))
counted = {}
count = 0
for i in s:
    if i in counted:
        count += counted[i]
    else:
        count += list(s).count(i)
print(count)


# Codeforces 50B
s = input()
count = 0
for i in range(s.__len__()):
    count += list(s).count(s[i])
print(count)


a=list(input());

s=0

for i in set(a):

    s=(a.count(i))**2

print(s)


a=list(input());s=0

for i in set(a):

    s+=(a.count(i))**2

print(s)


a=list(input())
s=0
for i in set(a)(
    s=(a.count(i))**2
print(s)


a=list(input());s=0

for i in set(a):

    s=(a.count(i))**2

print(s)


s = input()
l = 300*[0]
for i in s:
    l[ord(i)] = l[ord(i)] + 1

j = 0
for i in l:
    j = j + i*(i-1)

print (j + len(s))


s=list(input())
for i in range(len(s)):
    print(sum(a.count(i)**2))


s=input()
p=0
for i in set(s):
    p+=s.count(i)*s.count(i)
print(p)


s=list(input())
p=0
for i in set(s):
    p+=(a.count(i))**2
print(p)


s=list(input())
p=0
for i in set(s):
    p+=(s.count(i))**2
print(s)


s=input()
p=0
for i in set(s):
    p+=(s.count(i))**2
print(s)


s=list(input())
p=0
k=set(s)
for i in k:
    p+=(s.count(i))**2
print(P)


s=list(input())
p=0
for i in range(len(s)):
    p+=a.count(i)**2
print(p)


s=list(input())
p=0
for i in range(s):
    p+=(a.count(i))**2
print(p)


from collections import Counter
s=list(input())
t=Counter(s)
su=0
for i in t:
    su=su+t[i]*t[i]
print(su)


string = input()
ans=0
for iter in set(string):
    ans+=string.count(iter)**2
print(ans)


def help(n):
    return n*n
def fun(s):
    d={}
    for i in range(len(s)):
        if s[i] in d:
            d[s[i]].append(i)
        else:
            d[s[i]] = [i]

    c=0
    for i in d:
        c+=help(len(d[i]))
    return c
#n,m = list(map(int,input().split()))
#l = list(map(int,input().split()))

s= input()
print(fun(s))


word = input()

counts = {c: word.count(c) for c in set(word) }

print(sum(map(lambda val: val ** 2, counts.values())))


word = input()

counts = [ word.count(c) for c in set(word) ]

print(sum(map(lambda val: val ** 2, counts)))


s = input()
ans = 0
for i in range(len(s)):
    for j in range(len(s)):
        if s[i] == s[j]:
            ans += 1
print(ans)


s = input()
d = {}
for i in s:
    if i in d:
        d[i] += 1
    else:
        d[i] = 1
ans = 0
for i in d.values():
    ans += (i * (i - 1)) // 2
print(2 * ans + len(s))


s = input()
d = {}
for i in s:
    if i in d:
        d[i] += 1
    else:
        d[i] = 1
print(sum(map(lambda x: x * x,d.values())))


s = input()

t = len(s)

d = {}

for x in s:
    if x in d:
        d[x] = d[x] + 1
    else:
        d[x] = 1
k = 0
for v in d:
    k += d[v] * d[v]
print(k)


from collections import Counter
s = input()
c = Counter(s)
cnt = 0
for x in c:
    cnt += c[x]*c[x]
print(cnt)


from collections import defaultdict
p = defaultdict(int)
for i in input():
    p[i] += 1
print(sum(x * x for x in p.values()))


string=input()
arr=[0]*128
for r in range (len(string)):
    arr[ord(string[r])]+=1
total=0
for p in range (len(string)):
    total=total+arr[ord(string[r])]
print (total)


string=input()
arr=[0]*128
for r in range (len(string)):
    arr[ord(string[r])]+=1
total=0
myset=set(string)
for val in myset:
    total=total+(arr[ord(val)]**2)
print (total)


a=list(input());s=0

for i in set(a):

    s+=(a.count(i))**2

print(s)

# Made By Mostafa_Khaled


a=list(input())
s=0
b=[]
for i in a:
    if i not in b:
        b.append(i)
        l=a.count(i)
        s= s + l**2
print(s)


a=list(input())
s=0
b=[]
for i in set(a):
    l=a.count(i)
    s= s + l**2
print(s)


s = input()
res = 0
for i in set(s):
        res += s.count(i)*s.count(i)
print(res)


import random
import math
a = input()

l = len(a)

li = []
for i in range(0,l):
    li.append(a[i])

li.append('+')
li.sort()
li.reverse()
com = 1
list = []
for i in range(0,l):
    if li[i] == li[i + 1]:
        com += 1
        if i == l:
            list.append(com)
    else:
        list.append(com)
        com = 1

total = 0
for i in range(0,len(list)):
    if list[i] == 1:
        total = total + 1
    else:
        total = total + (list[i] * list[i])

print(total)


s=input()
dic={}
b=len(s)
counter=0
for i in range(b):
	t=s[i]
	if t in dic:
		dic[t]+=1
	else:
		dic[t]=1
for i in dic:
	counter=counter+(int(dic[i])**2)
print(counter)


a=list(input())
print(sum(a.count(i)**2 for i in set(a)))


def main(chars):
    counts = dict()

    for char in chars:
        try:
            counts[char] += 1
        except KeyError:
            counts[char] = 1

    squares = [char_count ** 2
               for char_count
               in counts.values()]

    return sum(squares)

if __name__ == "__main__":
    print(main(input()))


from collections import Counter
import math

#print ("Digite a string")
my_string = str (input())

counter = Counter (my_string)
#print (counter)
sum = 0
for line in counter:
    #print (str(counter[str(line)]))
    sum = sum + math.pow(int (counter[line]),2)

print (int(sum))


def symbol_pair(str):
    occurences = dict()
    for i in str:
        if i not in occurences:
            occurences[i] = 1
        else:
            occurences[i] += 1
    total = 0
    for key in occurences.keys():
        total += occurences[key] ** 2
    return total

print(symbol_pair(input()))


s = input()
s = [s.count(x) for x in set(s)]
print(sum(map(lambda x:x**2,s)))


S=str(input())
M=set(S)
c=0
for m in M:
    c+=(S.count(m))**2
print(c)


#!/usr/bin/python3

cnt = {}
for _ in list(input()):
    cnt[_] = cnt.get(_, 0) + 1
ans = 0
for _ in cnt.values():
    ans += _ + _ * (_ - 1)
print(ans)


#https://codeforces.com/contest/50/problem/B

import sys
import math

alpha = 'abcdefghijklmnopqrstuvwxyz0123456789'

def main():
    #sys.stdin = open('E:\\Sublime\\in.txt', 'r')
    #sys.stdout = open('E:\\Sublime\\out.txt', 'w')
    #sys.stderr = open('E:\\Sublime\\err.txt', 'w')

    s = list(sys.stdin.readline().strip())
    res = 0

    for c in alpha:
        res += s.count(c) ** 2

    print(res)

if __name__ == '__main__':
    main()

#hajj


s=input()
from collections import Counter
c=Counter(s)
ans=0
for i in c:
    ans=ans+(c[i]*(c[i]-1))+c[i]
print(ans)


s=input()
from collections import Counter
c=Counter(s)
ans=0
for i in c:
    ans=ans+(c[i]*(c[i]))
print(ans)


s = input()
d = {}
for i,x in enumerate(s):
    if d.get(x)==None:
        d[x]=0
    d[x]+=1
res=0
for i,x in enumerate(d):res+=d[x]**2
print(res)


def main():
	line = input()
	dicline = {}

	for c in line:
		if c in dicline.keys() :
			dicline[c] += 1
		else:
			dicline[c] = 1

	ans = 0
	for key, value in dicline.items():
		ans += value**2

	print(ans)

main()


S = input()
total = 0

for i in S:
	total += S.count(i)

print(total)


S = input()
total = 0

for i in S:
	for j in S:
		if j == i:
			total += 1

print(total)


S = list(input())
S.sort()

total = 0

while len(S)>0:
	i = S[0]
	t = S.count(i)
	total += t**2
	for j in range(t):
		del S[0]
print(total)


p=list(input())
sum=0
for i in set(p):
    sum=sum+p.count(i)**2
print(sum)


dict = {}

S = input();

for i in range (len(S)):
	if (S[i] in dict):
		dict[S[i]] += 1
	else:
		dict[S[i]] = 1

for key in dict:
	dict[key] *= dict[key]

print (sum(dict.values()))


#include <stdio.h>
#include <string.h>

int main (){
	int i = 0, j = 0;
	long int count = 0;
	char S[100010];

	fscanf(stdin, "%s", S);

	for (i=0; i<strlen(S); i++){
		for (j=0; j<strlen(S); j++){
			if (S[i] == S[j]){
				count ++;
			}
		}
	}

	printf("%ld\n", count);

	return 0;
}


'''
Solução de Problemas Computacionais - 2017/01
Carolina Coimbra Vieira - 2014032941
PROBLEMA: Choosing Symbol Pairs (Codeforces_CF50B)

O problema consiste em ler uma string S de tamanho N e determinar a quantidade de pares (i,j)
que podem ser formados de forma que 1 <= i, j <= N e S[i] = S[j]. Como os casos de teste são
individuais, a cada chamada do main, um dicionário é criado e a string S é lida. Após isso,
todos os caracteres da string são percorrido de forma que, caso algum deles esteja no dicionário,
basta incrementar o valor em 1 e, caso contrário, basta criar essa chave e inicializar seu valor
em 1. Após percorrer toda a string e completado o dicionário conforme descrito acima, basta
elevar todos os valores do dicionário à potência de 2 e somar todos eles. Isso significa que,
ao elevar a potência de 2, são gerados todos os pares com aquele caractere específico representado
pela chave do dicionário, uma vez que os pares devem ser formados pelo mesmo caractere, já que
uma das restrições do problema é que S[i] deve ser igual à S[j]. Uma informação importante é que
como foi descrito na especificação, os pares (1,2) e (2,1) são diferentes, ou seja, a ordem importa,
sendo assim, elevando à potência de 2, todos os pares são considerados. E, ao somar todos os valores
resultantes significa que todos os pares formados por todos os caracteres serão considerados.
Por fim, basta imprimir essa soma.

Tags = dicionário, atualização de valores em dicionário, soma de valores do dicionário, strings

'''

def main ():
	dict = {}

	S = input();

	for i in range (len(S)):

		if (S[i] in dict):
			dict[S[i]] += 1
		else:
			dict[S[i]] = 1

	for key in dict:
		dict[key] *= dict[key]

	print (sum(dict.values()))

main ()


'''
Solução de Problemas Computacionais - 2017/01
Carolina Coimbra Vieira - 2014032941
PROBLEMA: Choosing Symbol Pairs (Codeforces_CF50B)

O problema consiste em ler uma string S de tamanho N e determinar a quantidade de pares (i,j)
que podem ser formados de forma que 1 <= i, j <= N e S[i] = S[j]. Como os casos de teste são
individuais, a cada chamada do main, um dicionário é criado e a string S é lida. Após isso,
todos os caracteres da string são percorrido de forma que, caso algum deles esteja no dicionário,
basta incrementar o valor em 1 e, caso contrário, basta criar essa chave e inicializar seu valor
em 1. Após percorrer toda a string e completado o dicionário conforme descrito acima, basta
elevar todos os valores do dicionário à potência de 2 e somar todos eles. Isso significa que,
ao elevar a potência de 2, são gerados todos os pares com aquele caractere específico representado
pela chave do dicionário, uma vez que os pares devem ser formados pelo mesmo caractere, já que
uma das restrições do problema é que S[i] deve ser igual à S[j]. Uma informação importante é que
como foi descrito na especificação, os pares (1,2) e (2,1) são diferentes, ou seja, a ordem importa,
sendo assim, elevando à potência de 2, todos os pares são considerados. E, ao somar todos os valores
resultantes significa que todos os pares formados por todos os caracteres serão considerados.
Por fim, basta imprimir essa soma.

Tags = dicionário, atualização de valores em dicionário, soma de valores do dicionário, strings

'''

def main ():
	dict = {}

	S = input();

	for i in range (len(S)):
		if (S[i] in dict):
			dict[S[i]] += 1
		else:
			dict[S[i]] = 1

	for key in dict:
		dict[key] *= dict[key]

	print (sum(dict.values()))

main ()


from collections import defaultdict
s = input()
dic = defaultdict(int)
for i in s:
    dic[i] += 1

num = 0
for v in dic.values():
    num += v * v

print(num)


s = input()

count = {}

total = 0
for i in s:
    if ord(i) in count:
        count[ord(i)] += 1
        total += (count[ord(i)]*2-1)
    else:
        total += 1
        count[ord(i)] = 1

print(total)


s = input()

count = {}

for i in s:
    if ord(i) in count:
        count[ord(i)] += 1
    else:
        count[ord(i)] = 1

total = 0
for k in count:
    total += count[k]*count[k]

print(total)


s = input()

count = {}

total = 0
for i in s:
    if ord(i) in count:
        total -= count[ord(i)]**2
        count[ord(i)] += 1
        total += count[ord(i)]**2
    else:
        total += 1
        count[ord(i)] = 1

print(total)


s=input()
a=set(s)
ans=0
for i in a:
	#print(ans)
	ans+=(s.count(i))**2
print(ans)


#=================================
if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open("./input.txt", "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

line=gets.strip
hs=Hash.new(0)

line.each_char{|c|
	hs[c.ord]+=1
}

ans=0
hs.values.each{|v|
	ans+=v**2
}

puts ans


counter = Hash.new(0)
STDIN.read.gsub("\n", "").split("").each { |symbol| counter[symbol] += 1 }
puts counter.values.inject(0) { |res, count| res + count ** 2}


s = gets.chomp!

mas = Hash.new()
s.chars { |c|
  mas[c] == nil ? mas[c] = 1 : mas[c] += 1
}

sum = 0
mas.each_value {|d|
  sum += d**2
}

puts sum


s = gets.chomp!

count = 0
s.chars { |c1|
  s.chars { |c2|
    count += c1 == c2 ? 1 : 0
  }
}

puts count


S = raw_input()
sz = len(S)
dic = {}
for i in xrange(sz):
  dic[S[i]] = dic.get(S[i], 0) + 1
ans = 0
for v in dic.values():
  ans += v*v
print ans


from collections import defaultdict

d = defaultdict(int)
for c in raw_input().strip():
	d[c] += 1
for c in d:
	d[c] = d[c]**2
print sum(d[c] for c in d)


s = list(raw_input())
print sum([s.count(i) for i in s])


s = list(raw_input())
print sum([s.count(i)**2 for i in set(s)])


#!/usr/bin/python

s = raw_input()
c = {}
for a in s:
    c[a] = c.get(a, 0) + 1
res = 0
for v in c.values():
    res += v*v
print res


s = raw_input()
l = [0 for i in range(256)]
for i in s:
    l[ord(i)] += 1
sum = 0
for i in l: sum += i ** 2
print sum


s = raw_input()
l = []
k = 1
for i in range(len(s)-1):
    if(s[i] == s[i+1]): k += 1
    else:
        l.append(k)
        k = 1
l.append(k)
sum = 0
for i in l: sum += i ** 2
print sum


__author__ = 'Azad'

import string

n = raw_input()
all = string.ascii_lowercase + string.digits

l = [n.count(x) for x in all]

print sum([x*x for x in l])


numChar = {}

s = raw_input()

for i in xrange(len(s)):
	if s[i] in numChar:
		numChar[s[i]] += 1
	else:
		numChar[s[i]] = 1

numPairs = 0
for i in xrange(len(s)):
	numPairs += numChar[s[i]]

print numPairs


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int n = input.nextInt();
        int[][] data = new int[n][3];
        boolean sum = true;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < data[i].length; j++) {
                data[i][j] = input.nextInt();
            }
        }

        for (int i = 0; i < n; i++) {
            int total = 0;
            for (int j = 0; j < 3; j++) {
                total = total + data[j][i];
            }
            if (total != 0) {
                sum = false;
                break;
            }
        }

        System.out.println(sum ? "YES" : "NO");
    }

}


import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        int n = input.nextInt();
        int [] [] data = new int [n] [3];

        int sum = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < data[i].length; j++) {
                data [i] [j] = input.nextInt();
                sum = sum + data[i] [j];
            }
        }

        System.out.println(sum == 0 ? "YES" : "NO" );
    }

}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int n = input.nextInt();
        int[][] data = new int[n][3];
        boolean sum = true;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < data[i].length; j++) {
                data[i][j] = input.nextInt();
            }
        }

        for (int i = 0; i < 3; i++) {
            int total = 0;
            for (int j = 0; j < n; j++) {
                total = total + data[j][i];
            }
            if (total != 0) {
                sum = false;
                break;
            }
        }

        System.out.println(sum ? "YES" : "NO");
    }

}


import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        int n = input.nextInt();
        int [] [] data = new int [n] [3];
        boolean sum = true;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < data[i].length; j++) {
                data [i] [j] = input.nextInt();
            }
        }

        for (int i = 0; i < n; i++) {
            if(data [i][0] + data[i][1] + data[0][2] != 0){
                sum = false;
                break;
            }
        }

        System.out.println(sum ? "YES" : "NO" );
    }

}


//package codebat;

import java.util.Scanner;

public class CodeForce {
    public static void main(String[] args) {
        int n;
        boolean vector = true;
        int s;
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        int[][] in = new int[n][n];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 3; j++) {
                in[i][j] = sc.nextInt();
            }
        }
        for (int i = 0; i < 3; i++) {
            s = 0;
            for (int j = 0; j < in.length; j++) {
                s = s + in[j][i];
            }
            System.out.println(s);
            if (s != 0)
                vector = false;
        }
        if (vector == true)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}


//package codebat;

import java.util.Scanner;

public class CodeForce {
    public static void main(String[] args) {
        int n;
        boolean vector=true;
        int s=0;
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        int[][] in = new int[n][n];

        for (int i = 0; i < n; i++) {
            for(int j=0;j<n;j++){
                in[i][j]=sc.nextInt();
            }
        }
        for(int i=0;i<in.length;i++){
            s=0;
            for(int j=0;j<in.length;j++){
                s=s+in[j][i];
            }
           if(s!=0)
               vector=false;
        }
        if(vector==true)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}


//package codebat;

import java.util.Scanner;

public class CodeForce {
    public static void main(String[] args) {
        int n;
        boolean vector = true;
        int s;
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        int[][] in = new int[n][3];

        for (int i = 0; i < n; i++) {
            s = 0;
            for (int j = 0; j < 3; j++) {
                in[i][j] = sc.nextInt();
                s = s + in[j][i];
            }
            if (s != 0)
                vector = false;
        }
        if (vector == true)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}


//package codebat;

import java.util.Scanner;

public class CodeForce {
    public static void main(String[] args) {
        int n;
        boolean vector = true;
        int s = 0;
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        int[][] in = new int[n][n];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 3; j++) {
                in[i][j] = sc.nextInt();
            }
        }
        for (int i = 0; i < in.length; i++) {
            s = 0;
            for (int j = 0; j < 3; j++) {
                s = s + in[j][i];
            }
            if (s != 0)
                vector = false;
        }
        if (vector == true)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}


//package codebat;

import java.util.Scanner;

public class CodeForce {
    public static void main(String[] args) {
        int n;
        boolean vector = true;
        int s;
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        int[][] in = new int[n][3];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 3; j++) {
                in[i][j] = sc.nextInt();
            }
        }
        for (int i = 0; i < 3; i++) {
            s = 0;
            for (int j = 0; j < in.length; j++) {
                s = s + in[j][i];
            }
            if (s != 0)
                vector = false;
        }
        if (vector == true)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}


//package codebat;

import java.util.Scanner;

public class CodeForce {
    public static void main(String[] args) {
        int n;
        boolean vector = true;
        int s;
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        int[][] in = new int[n][n];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 3; j++) {
                in[i][j] = sc.nextInt();
            }
        }
        for (int i = 0; i < 3; i++) {
            s = 0;
            for (int j = 0; j < in.length; j++) {
                s = s + in[j][i];
            }
            if (s != 0)
                vector = false;
        }
        if (vector == true)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}


import java.util.*;
import java.io.*;

public class A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0;

        for(int i=0; i<n; i++) {
            int[] arr = new int[n];
            for(int j=0; j<n; j++) {
                int temp = sc.nextInt();
                arr[i] = temp;
            }
            ans+=Arrays.stream(arr).sum();
        }

        if(ans>0) {
            System.out.println("NO");
        } else {
            System.out.println("YES");
        }

    }
}


import java.util.*;
import java.io.*;

public class A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0;

        for(int i=0; i<n; i++) {
            int[] arr = new int[n];
            for(int j=0; j<3; j++) {
                int temp = sc.nextInt();
                arr[i] = temp;
            }
            ans+=Arrays.stream(arr).sum();
        }

        if(ans!=0) {
            System.out.println("NO");
        } else {
            System.out.println("YES");
        }

    }
}


import java.util.*;
import java.io.*;

public class A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0;
        int[] arr = new int[3];

        for(int i=0; i<n; i++) {
            for(int j=0; j<3; j++) {
                int temp = sc.nextInt();
                ans+=temp;
            }
            arr[i] = ans;
            ans = 0;
        }

        ans = Arrays.stream(arr).sum();

        if(ans != 0) {
            System.out.println("NO");
        } else {
            System.out.println("YES");
        }

    }
}


import java.util.*;
import java.io.*;

public class A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0;
        int[] arr = new int[n];

        for(int i=0; i<n; i++) {
            for(int j=0; j<3; j++) {
                int temp = sc.nextInt();
                ans+=temp;
            }
            arr[i] = ans;
            ans = 0;
        }

        ans = Arrays.stream(arr).sum();

        if(ans != 0) {
            System.out.println("NO");
        } else {
            System.out.println("YES");
        }

    }
}


import java.util.*;
import java.io.*;

public class A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0;

        for(int i=0; i<n; i++) {
            int[] arr = new int[n];
            for(int j=0; j<3; j++) {
                int temp = sc.nextInt();
                arr[i] = temp;
            }
            ans+=Arrays.stream(arr).sum();
        }

        if(ans>0) {
            System.out.println("NO");
        } else {
            System.out.println("YES");
        }

    }
}


import java.util.*;
import java.io.*;

public class A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0;

        for(int i=0; i<n; i++) {
            for(int j=0; j<3; j++) {
                int temp = sc.nextInt();
                ans+=temp;
            }
        }

        if(ans!=0) {
            System.out.println("NO");
        } else {
            System.out.println("YES");
        }

    }
}


import java.util.*;
import java.io.*;

public class A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0;
        int[] arr = new int[n];

        for(int i=0; i<n; i++) {
            for(int j=0; j<3; j++) {
                int temp = sc.nextInt();
                ans+=temp;
            }
            arr[i] = ans;
            ans = 0;
        }

        for(int x: arr) {
            if(x != 0) {
                System.out.println("NO");
                System.exit(0);
            }
        }
        System.out.println("YES");
    }
}


import java.util.*;
import java.io.*;

public class A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0;

        for(int i=0; i<n; i++) {
            for(int j=0; j<3; j++) {
                int temp = sc.nextInt();
                ans+=temp;
            }
        }

        System.out.println(ans);

        if(ans!=0) {
            System.out.println("NO");
        } else {
            System.out.println("YES");
        }

    }
}


import java.util.*;
import java.io.*;

public class A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0;
        int[] arr = new int[3];

        for(int i=0; i<n; i++) {
            for(int j=0; j<3; j++) {
                int temp = sc.nextInt();
                ans+=temp;
            }
            arr[i] = ans;
        }

        ans = Arrays.stream(arr).sum();
        if(ans != 0) {
            System.out.println("NO");
        } else {
            System.out.println("YES");
        }

    }
}


import java.util.*;
import java.io.*;

public class A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int ans = 0;
        int[][] arr = new int[n][3];

        for(int i=0; i<n; i++) {
            for(int j=0; j<3; j++) {
                int temp = sc.nextInt();
                arr[i][j] = temp;
            }
        }

        for(int j=0; j<3; j++) {
            for(int i=0; i<n; i++) {
                ans+=arr[i][j];
            }
            if(ans != 0) {
                System.out.println("NO");
                System.exit(0);
            }
            ans = 0;
        }
        System.out.println("YES");
    }
}


import java.util.Scanner;

public class bhaskar
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int x=0;
        int y=0;
        int z=0;
        for(int i=0;i<n;i++)
        {
            x+=sc.nextInt();
            y+=sc.nextInt();
            z+=sc.nextInt();
        }
        if(x==0 && y==0 && z==0)
        System.out.println("YES");
        else
        System.out.println("NO");
    }
}


import java.util.Scanner;
public class Youngphysicst {
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int x=0;
        int y=0;
        int z=0;
        for(int i=0;i<n;i++)
        {
            x=x+sc.nextInt();
            y=y+sc.nextInt();
            z=z+sc.nextInt();
        }
        if(x==0 && y==0 && z==0)
        {

            System.out.println("YES");
        }
        else
        {
            System.out.println("NO");
        }
    }
}


import java.util.Scanner;

public class physicist
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        int x=0;
        int y=0;
        int z=0;
        int n=sc.nextInt();
        for(int i=0;i<n;i++)
        {
            x=x+sc.nextInt();
            y=y+sc.nextInt();
            z=z+sc.nextInt();
        }
        if((x==0 && y==0)&& z==0)
        {
            System.out.println("YES");

        }
        else
        {
            System.out.println("NO");
        }
    }
}


import java.util.*;
public class Equilibrium{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        int f=sc.nextInt();
        int x=0,y=0,z=0;
        for(int i=0;i<f;i++)
        {
            x=x+sc.nextInt();
            y=y+sc.nextInt();
            z=z+sc.nextInt();
        }
        if(x==0 && y==0 && z==0)
        {
            System.out.println("YES");
        }
        else
        System.out.println("NO");
    }
}


import java.util.Scanner;

public class physicist
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        int x=0;
        int y=0;
        int z=0;
        int n=sc.nextInt();
        while(n-->0)
        {
            x=x+sc.nextInt();
            y=y+sc.nextInt();
            z=z+sc.nextInt();
        }
        if(x==0 && y==0 && z==0)
        {
            System.out.println("YES");

        }
        else
        {
            System.out.println("NO");
        }
    }
}


import java.util.Scanner;

public class physicist
{
    public static void main(String arg[])
    {
        Scanner sc=new Sacnner(System.in);
        int x=0;
        int y=0;
        int z=0;
        int n=sc.nextInt();
        for(int i=0;i<n;i++)
        {
            x=x+sc.nextInt();
            y=y+sc.nextInt();
            z=z+sc.nextInt();
        }
        if((x==0 && y==0)&& z==0)
        {
            System.out.println("YES");

        }
        else
        {
            System.out.println("NO");
        }
    }
}


import java.util.Scanner;

public class physicist
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        int x=0;
        int y=0;
        int z=0;
        int n=sc.nextInt();
        for(int i=0;i<n;i++)
        {
            x=x+sc.nextInt();
            y=y+sc.nextInt();
            z=z+sc.nextInt();
        }
        if(x==0 && y==0&& z==0)
        {
            System.out.println("YES");

        }
        else
        {
            System.out.println("NO");
        }
    }
}


import java.util.Scanner;

public class Young{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int x=0;y=0;z=0;
        for(int i=0;i<n;i++)
        {
            x=x+sc.nextInt();
            y=y+sc.nextInt();
            z=z+sc.nextInt();
        }
        if(x==0 && y==0 && z==0)
        {
            System.out.println("YES");
        }
        else
        {
            System.out.println("NO");
        }
    }
}


import java.util.Scanner;

public class physicist
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        int x=0;
        int y=0;
        int z=0;
        int n=sc.nextInt();
        while(n--0)
        {
            x=x+sc.nextInt();
            y=y+sc.nextInt();
            z=z+sc.nextInt();
        }
        if(x==0 && y==0 && z==0)
        {
            System.out.println("YES");

        }
        else
        {
            System.out.println("NO");
        }
    }
}


import java.util.Scanner;

public class physicist
{
    public static void main(String arg[])
    {
        Scanner sc=new Sacnner(String arg[])
        int x=0;
        int y=0;
        int z=0;
        int n=sc.nextInt();
        for(int i=0;i<n;i++)
        {
            x=x+sc.nextInt();
            y=y+sc.nextInt();
            z=z+sc.nextInt();
        }
        if((x==0 && y==0)&& z==0)
        {
            System.out.println("YES");

        }
        else
        {
            System.out.println("NO");
        }
    }
}


import java.util.Scanner;
public class YoungPhys {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int x=0;
        int y=0;
        int z=0;
        for(int i=1;i<=n;i++)
        {
            x=x+sc.nextInt();
            y=y+sc.nextInt();
            z=z+sc.nextInt();
        }
        if(x==0 && y==0 && z==0)
        {
            System.out.println("YES");
        }
        else
            System.out.println("NO");

    }
}


import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;

public class newclass {

	@SuppressWarnings("unlikely-arg-type")
	public static void main(String[] args) {
	    Scanner sc =new Scanner(System.in);
		int n = sc.nextInt();
		int []arr = new int[n] ;

		int n1=0,n2=0,n3= 0 ;

		for (int i = 0; i < arr.length; i++) {

		    	   n1 = n1 +sc.nextInt();

		    	   n2  = n2 + sc.nextInt();

		    	   n3 = n3 +sc.nextInt();
		}

		if(n1 == 0 &&+n2== 0&&n3 == 0)
			System.out.println("YES");
		else
			System.out.println("NO");

		}

		}


import java.util.Scanner;

public class physicist
{
    public static void main(String arg[])
    {
        Scanner sc=new Scanner(System.in);
        int x=0;
        int y=0;
        int z=0;
        int n=sc.nextInt();
        while(n-->0)
        {
            x=x+sc.nextInt();
            y=y+sc.nextInt();
            z=z+sc.nextInt();
        }
        if((x==0 && y==0)&& z==0)
        {
            System.out.println("YES");

        }
        else
        {
            System.out.println("NO");
        }
    }
}


import java.util.Scanner;

public class JavaApplication12 {
    public static void main(String[] args) {

        int n ;
        int sum = 0;
        Scanner sc = new Scanner (System.in);
        n = sc.nextInt();

        for (int i=0 ; i<n ;i++)
        {
       int x;
       x= sc.nextInt();
       sum += x;
            System.out.print("");
        }
         for (int i=0 ; i<n ;i++)
        {
       int x;
       x= sc.nextInt();
       sum += x;
       System.out.print("");
        }
          for (int i=0 ; i<n ;i++)
        {
       int x;
       x= sc.nextInt();
       sum += x;
       System.out.print("");
        }
          if(sum == 0 )
              System.out.println("Yes");
          else
              System.out.println("No");
    }
}


import java.util.Scanner;

public class JavaApplication12 {

    public static void main(String[] args) {

        int n ;
        int sum = 0;
        Scanner sc = new Scanner (System.in);
        n = sc.nextInt();

        int arr[][]=new int[3][n];
        for(int i =0;i<3;i++)
        {
            for(int j=0 ; j<n;j++)
            {
                arr[i][j]=sc.nextInt();
                sum += arr[i][j];
            }
        }
        if(sum==0)
            System.out.println("Yes");
        else
            System.out.println("No");

    }
}


import java.util.Scanner;

public class JavaApplication12 {
    public static void main(String[] args) {
        // TODO code application logic here
        int n ;
        int sum ;
        Scanner sc = new Scanner (System.in);
        n = sc.nextInt();

    //    int arr[][]=new int[n][3];
       int sumx = 0;
        for(int i =0;i<n;i++)
        {
          int x = sc.nextInt();
          sumx+=x;
        }
        int sumy =0;
        for(int i =0;i<n;i++)
        {
          int x = sc.nextInt();
          sumy+=x;
        }
        int sumz=0;
        for(int i =0;i<n;i++)
        {
          int x = sc.nextInt();
          sumz+=x;
        }
        sum = sumx+sumy+sumz;
        if(sum==0)
            System.out.println("Yes");
        else
        System.out.println("No");
    }

}


import java.util.Scanner;

public class JavaApplication12 {
   public static void main(String[] args) {
        // TODO code application logic here
        int n ;
        int sum = 0;
        Scanner sc = new Scanner (System.in);
        n = sc.nextInt();

        int arr[][]=new int[n][3];
        for(int i =0;i<n;i++)
        {
            for(int j=0 ; j<3;j++)
            {
                arr[i][j]=sc.nextInt();
                sum += arr[i][j];
            }
        }
        if(sum==0)
            System.out.println("Yes");
        else
            System.out.println("No");

    }
}


import java.util.Scanner;

public class JavaApplication12 {

    public static void main(String[] args) {
            int n ;
        int sum = 0;
        Scanner sc = new Scanner (System.in);
        n = sc.nextInt();

        int arr[][]=new int[n][3];
        for(int i =0;i<n;i++)
        {
            for(int j=0 ; j<3;j++)
            {
                arr[i][j]=sc.nextInt();
                sum += arr[i][j];
            }
        }
        if(sum==0)
            System.out.println("yes");
        else
            System.out.println("no");

    }
}


import java.util.Scanner;

public class JavaApplication14 {

    static char grid[][];

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int sum[]= new int [3];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 3; j++) {
                sum[j]+=scanner.nextInt();
            }
        }
        for (int i = 0; i < sum.length; i++) {
            if(sum[i]!=0){
                System.out.println("NO");
                return;
            }
        }
        System.out.println("YES");
    }

}


import java.util.Scanner;

public class JavaApplication12 {

    public static void main(String[] args) {
        // TODO code application logic here
        int n ;
        int k=0;
        int sum=0 ;
        Scanner sc = new Scanner (System.in);
        n = sc.nextInt();
       int arr[][]=new int[3][n];
       int ar[]=new int[n];
       for(int i=0; i<3;i++)
       {
           for(int j=0;j<n;j++)
           {
           arr[i][j]=sc.nextInt();
           }
       }
       for(int j=0;j<n;j++)
       {
           for(int i=0;i<3;i++)
           {
               sum+=arr[i][j];
           }
           ar[k]=sum;
           k++;

      }
       int sumb=0;
       for(int i=0;i<n;i++)
       {
           sumb+=ar[i];
       }
       if(sumb==0)
           System.out.println("yes");
       else
           System.out.println("no");

    }
}


import java.util.Scanner;

public class JavaApplication12 {

    public static void main(String[] args) {

        int n ;
        int k=0;
        int sum=0 ;
        Scanner sc = new Scanner (System.in);
        n = sc.nextInt();
       int arr[][]=new int[3][n];
       int ar[]=new int[n];
       for(int i=0; i<3;i++)
       {
           for(int j=0;j<n;j++)
           {
           arr[i][j]=sc.nextInt();
           }
       }
       for(int i=0;i<n;i++)
       {
           for(int j=0;j<3;i++)
           {
               sum+=arr[i][j];
           }
           ar[k]=sum;
           k++;

      }
       int sumb=0;
       for(int i=0;i<n;i++)
       {
           sumb+=ar[i];
       }
       if(sumb==0)
           System.out.println("yes");
       else
           System.out.println("no");

    }
}


import java.util.Scanner;

public class JavaApplication12 {

        public static void main(String[] args) {
        // TODO code application logic here
        int n ;
        int sum = 0;
        Scanner sc = new Scanner (System.in);
        n = sc.nextInt();

        for (int i=0 ; i<n ;i++)
        {
       int x;
       x= sc.nextInt();
       sum += x;
            System.out.print("");
        }
         for (int i=0 ; i<n ;i++)
        {
       int x;
       x= sc.nextInt();
       sum += x;
       System.out.print("");
        }
          for (int i=0 ; i<n ;i++)
        {
       int x;
       x= sc.nextInt();
       sum += x;
       System.out.print("");
        }
          if(sum == 0 )
              System.out.println("Yes");
          else
              System.out.println("No");
    }
}


import java.util.Scanner;

public class JavaApplication12 {

    public static void main(String[] args) {

        int n ;
        int k=0;
        int sum=0 ;
        Scanner sc = new Scanner (System.in);
        n = sc.nextInt();
       int arr[][]=new int[3][n];
       int ar[]=new int[n];
       for(int i=0; i<3;i++)
       {
           for(int j=0;j<n;j++)
           {
           arr[i][j]=sc.nextInt();
           }
       }
       for(int i=0;i<3;i++)
       {
           for(int j=0;j<n;j++)
           {
               sum +=arr[i][j];
           }
           ar[k]=sum;
           k++;

      }
       int sumb=0;
       for(int i=0;i<n;i++)
       {
           sumb+=ar[i];
       }
       if(sumb==0)
           System.out.println("yes");
       else
           System.out.println("no");

    }
}


import java.util.Scanner;

/**
 *
 * @author fathy4
 */
public class JavaApplication12 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        int n ;
        int sum = 0;
        Scanner sc = new Scanner (System.in);
        n = sc.nextInt();

        for (int i=0 ; i<n ;i++)
        {
       int x;
       x= sc.nextInt();
       sum += x;
            System.out.print("");
        }
         for (int i=0 ; i<n ;i++)
        {
       int x;
       x= sc.nextInt();
       sum += x;
       System.out.print("");
        }
          for (int i=0 ; i<n ;i++)
        {
       int x;
       x= sc.nextInt();
       sum += x;
       System.out.print("");
        }
          if(sum == 0 )
              System.out.println("Yes");
          else
              System.out.println("No");
    }
}


import java.util.Scanner;

public class Main
{
	public static void main(String args[])
	{
		Scanner scan=new Scanner(System.in);
		int N=scan.nextInt();

		int[] num=new int[N];
		for(int i=0;i<N*N;i++)
		{
				num[i]=0;
				num[i%N]+=s.nextInt();
		}

		int check=0;
		for(int i=0;i<N;i++)
		{
			if(num[i]!=0)
			{
				check=1;
				break;
			}

		}
		if(check==1)
		{
			System.out.println("NO");
		}
		else
			System.out.println("YES");
	}
}


import java.util.Scanner;

public class Main
{
	public static void main(String args[])
	{
		Scanner scan=new Scanner(System.in);
		int N=scan.nextInt();

		int[] num=new int[N];
		for(int i=0;i<N*N;i++)
		{
			if(num[i%N]==null)
				num[i%N]=0;
				num[i%N]+=scan.nextInt();
		}

		int check=0;
		for(int i=0;i<N;i++)
		{
			if(num[i]!=0)
			{
				check=1;
				break;
			}

		}
		if(check==1)
		{
			System.out.println("NO");
		}
		else
			System.out.println("YES");
	}
}


import java.util.Scanner;

public class Main
{
	public static void main(String args[])
	{
		Scanner scan=new Scanner(System.in);
		int N=scan.nextInt();

		int[] num=new int[3];
		for(int i=0;i<3;i++)
		{
				num[i]=0;//scan.nextInt();
		}
		for(int i=0;i<(N*3);i++)
		{
				num[i%3]+=scan.nextInt();
		}

		int check=0;
		for(int i=0;i<3;i++)
		{
			if(num[i]!=0)
			{
				check=1;
				break;
			}

		}
		if(check==1)
		{
			System.out.println("NO");
		}
		else
			System.out.println("YES");
	}
}


import java.util.Scanner;

public class Main
{
	public static void main(String args[])
	{
		Scanner scan=new Scanner(System.in);
		int N=scan.nextInt();

		int[] num=new int[N];
		for(int i=0;i<N;i++)
		{
				num[i]=0;//scan.nextInt();
		}
		for(int i=0;i<N*N;i++)
		{
				num[i%N]+=scan.nextInt();
		}

		int check=0;
		for(int i=0;i<N;i++)
		{
			if(num[i]!=0)
			{
				check=1;
				break;
			}

		}
		if(check==1)
		{
			System.out.println("NO");
		}
		else
			System.out.println("YES");
	}
}


import java.util.Scanner;

public class Main
{
	public static void main(String args[])
	{
		Scanner scan=new Scanner(System.in);
		int N=scan.nextInt();

		int[] num=new int[N];
		for(int i=0;i<N;i++)
		{
				num[i]=0;//scan.nextInt();
		}
		for(int i=0;i<N*3;i++)
		{
				num[i%N]+=scan.nextInt();
		}

		int check=0;
		for(int i=0;i<N;i++)
		{
			if(num[i]!=0)
			{
				check=1;
				break;
			}

		}
		if(check==1)
		{
			System.out.println("NO");
		}
		else
			System.out.println("YES");
	}
}


import java.util.Scanner;

public class Main
{
	public static void main(String args[])
	{
		Scanner scan=new Scanner(System.in);
		int N=scan.nextInt();

		int[] num=new int[3];
		for(int i=0;i<3;i++)
		{
				num[i]=0;//scan.nextInt();
		}
		for(int i=0;i<N*3;i++)
		{
				num[i%N]+=scan.nextInt();
		}

		int check=0;
		for(int i=0;i<N;i++)
		{
			if(num[i]!=0)
			{
				check=1;
				break;
			}

		}
		if(check==1)
		{
			System.out.println("NO");
		}
		else
			System.out.println("YES");
	}
}


import java.util.Scanner;

public class Main
{
	public static void main(String args[])
	{
		Scanner scan=new Scanner(System.in);
		int N=scan.nextInt();

		int[] num=new int[3];
		for(int i=0;i<3;i++)
		{
				num[i]=0;//scan.nextInt();
		}
		for(int i=0;i<N*3;i++)
		{
				num[i%3]+=scan.nextInt();
		}

		int check=0;
		for(int i=0;i<N;i++)
		{
			if(num[i]!=0)
			{
				check=1;
				break;
			}

		}
		if(check==1)
		{
			System.out.println("NO");
		}
		else
			System.out.println("YES");
	}
}


import java.util.Scanner;

public class Main
{
	public static void main(String args[])
	{
		Scanner scan=new Scanner(System.in);
		int N=scan.nextInt();

		int[] num=new int[N];
		for(int i=0;i<N*N;i++)
		{
				num[i]=0;
				num[i%N]+=scan.nextInt();
		}

		int check=0;
		for(int i=0;i<N;i++)
		{
			if(num[i]!=0)
			{
				check=1;
				break;
			}

		}
		if(check==1)
		{
			System.out.println("NO");
		}
		else
			System.out.println("YES");
	}
}


import java.util.Scanner;

public class Main
{
	public static void main(String args[])
	{
		Scanner scan=new Scanner(System.in);
		int N=scan.nextInt();

		int[] num=new int[N];
		for(int i=0;i<N;i++)
		{
				num[i]=0;//scan.nextInt();
		}
		for(int i=0;i<N*3;i++)
		{
				num[i%3]+=scan.nextInt();
		}

		int check=0;
		for(int i=0;i<N;i++)
		{
			if(num[i]!=0)
			{
				check=1;
				break;
			}

		}
		if(check==1)
		{
			System.out.println("NO");
		}
		else
			System.out.println("YES");
	}
}


import java.util.Scanner;
  public class YoungPhysicist {
    public static void main(String[] args) {
     Scanner input = new Scanner(System.in);
     int n = input.nextInt();

      int[][]Q = new int [n][3];
      int[]s = new int[3];
        for(int i=0; i<n;i++){
                for(int j=0;j<3;j++){
                    Q[i][j]=input.nextInt();
                       }
            }
            for(int j=0;j<3;j++){
            int U =0;
            for(int i=0;i<n;i++){
                U+=Q[i][j];
            }
                        s[j]=U;

            }

                if(s[0]==0&&s[1]==0&&s[2]==0){
                System.out.println("YES");
                }
                else
                    System.out.println("NO");

        }

    }


import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
       // System.out.print("Enter n vectors :");
        int n = input.nextInt();
        if(n>=1&&n<=100){
            int[][]Q = new int [n][3];  // n rows , 3 colomns
            int[]s = new int[3];
            for(int i=0; i<n;i++){
              //  System.out.println("Enter x,y,z for n "+i);
                for(int j=0;j<3;j++){
                    Q[i][j]=input.nextInt();
                }
            }
            for(int j=0;j<3;j++){
            int U =0;
            for(int i=0;i<n;i++){
                U+=Q[i][j];
            }
                        s[j]=U;

            }

                if(s[0]==0&&s[1]==0&&s[2]==0){
                System.out.println("YES");
                }
                else
                    System.out.println("NO");

        }
        else
        System.out.print("n should be 1<=n<=100");

    }

}


public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
       // System.out.print("Enter n vectors :");
        int n = input.nextInt();
        if(n>=1&&n<=100){
            int[][]Q = new int [n][3];  // n rows , 3 colomns
            int[]s = new int[3];
            for(int i=0; i<n;i++){
              //  System.out.println("Enter x,y,z for n "+i);
                for(int j=0;j<3;j++){
                    Q[i][j]=input.nextInt();
                }
            }
            for(int j=0;j<3;j++){
            int U =0;
            for(int i=0;i<n;i++){
                U+=Q[i][j];
            }
                        s[j]=U;

            }

                if(s[0]==0&&s[1]==0&&s[2]==0){
                System.out.println("YES");
                }
                else
                    System.out.println("NO");

        }
        else
        System.out.print("n should be 1<=n<=100");

    }

}


package young.physicist;
import java.util.Scanner;
public class YoungPhysicist {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
       // System.out.print("Enter n vectors :");
        int n = input.nextInt();
        if(n>=1&&n<=100){
            int[][]Q = new int [n][3];  // n rows , 3 colomns
            int[]s = new int[3];
            for(int i=0; i<n;i++){
              //  System.out.println("Enter x,y,z for n "+i);
                for(int j=0;j<3;j++){
                    Q[i][j]=input.nextInt();
                }
            }
            for(int j=0;j<3;j++){
            int U =0;
            for(int i=0;i<n;i++){
                U+=Q[i][j];
            }
                        s[j]=U;

            }

                if(s[0]==0&&s[1]==0&&s[2]==0){
                System.out.println("YES");
                }
                else
                    System.out.println("NO");

        }
        else
        System.out.print("n should be 1<=n<=100");

    }

}


package youngphysicist;
import java.util.Scanner;
  public class YoungPhysicist {
    public static void main(String[] args) {
     Scanner input = new Scanner(System.in);
     int n = input.nextInt();

      int[][]Q = new int [3][n];
      int[]s = new int[3];
        for(int i=0; i<n;i++){
                for(int j=0;j<3;j++){
                    Q[i][j]=input.nextInt();
                       }
            }
            for(int j=0;j<3;j++){
            int U =0;
            for(int i=0;i<n;i++){
                U+=Q[i][j];
            }
                        s[j]=U;

            }

                if(s[0]==0&&s[1]==0&&s[2]==0){
                System.out.println("YES");
                }
                else
                    System.out.println("NO");

        }

    }


package youngphysicist;
import java.util.Scanner;
  public class YoungPhysicist {
    public static void main(String[] args) {
     Scanner input = new Scanner(System.in);
     int n = input.nextInt();

      int[][]Q = new int [n][3];
      int[]s = new int[3];
        for(int i=0; i<n;i++){
                for(int j=0;j<3;j++){
                    Q[i][j]=input.nextInt();
                       }
            }
            for(int j=0;j<3;j++){
            int U =0;
            for(int i=0;i<n;i++){
                U+=Q[i][j];
            }
                        s[j]=U;

            }

                if(s[0]==0&&s[1]==0&&s[2]==0){
                System.out.println("YES");
                }
                else
                    System.out.println("NO");

        }

    }


//package a;

import java.util.Scanner;

public class YoungPhysicist {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner k = new Scanner(System.in);
		int x = k.nextInt();
		int[][] a = new int[3][x];
		int sum=0;
		int sum2=0;
		int sum3=0;
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < x; j++) {
				a[i][j] = k.nextInt();
			if (i==0) {
				sum+=a[i][j];
			}
			else if (i==1) {
				sum2+=a[i][j];
			}
			else{
				sum3+=a[i][j];
			}
			}
		}
if (sum==0&&sum2==0 &&sum3==0) {
	System.out.println("YES");
}
else{
	System.out.println("NO");
}
	}

}


//package a;

import java.util.Scanner;

public class YoungPhysicist {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner k = new Scanner(System.in);
		int x = k.nextInt();
		int[][] a = new int[3][x];
		int sum = 0;
		int sum2 = 0;
		int sum3 = 0;
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < x; j++) {
				a[i][j] = k.nextInt();
				if (j == 0) {
					sum += a[i][j];
				} else if (j == 1) {
					sum2 += a[i][j];
				} else {
					sum3 += a[i][j];
				}
			}
		}
		if (sum == 0 && sum2 == 0 && sum3 == 0) {
			System.out.println("YES");
		} else {
			System.out.println("NO");
		}
	}

}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner k = new Scanner(System.in);
		int x = k.nextInt();
		int[][] a = new int[x][x];
		long sum=0;
		for (int i = 0; i < x; i++) {
			for (int j = 0; j < x; j++) {
				a[i][j] = k.nextInt();
			sum+=a[i][j];
			}
		}
if (sum==0) {
	System.out.println("YES");
}
else{
	System.out.println("NO");
}
	}

}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner k = new Scanner(System.in);
		int x = k.nextInt();
		int[][] a = new int[x][x];
		int sum=0;
		for (int i = 0; i < x; i++) {
			for (int j = 0; j < x; j++) {
				a[i][j] = k.nextInt();
			sum+=a[i][j];
			}
		}
if (sum==0) {
	System.out.println("YES");
}
else{
	System.out.println("NO");
}
	}

}