//Shirasu Azusa 2024.7
#include <bits/stdc++.h>
#define fi first
#define se second
#define eb emplace_back
#define mp make_pair
using namespace std;
typedef long double ld;
typedef long long ll;
typedef unsigned long long ull;
typedef __int128 i128;
template<class T,class S>
bool chmax(T &a,const S b) {return (a<b?a=b,1:0);}
template<class T,class S>
bool chmin(T &a,const S b) {return (a>b?a=b,1:0);}
int popcnt(int x) {return __builtin_popcount(x);}
int popcnt(ll x) {return __builtin_popcountll(x);}
int topbit(int x) {return (x==0?-1:31-__builtin_clz(x));}
int topbit(ll x) {return (x==0?-1:63-__builtin_clzll(x));}
int lowbit(int x) {return (x==0?-1:__builtin_ctz(x));}
int lowbit(ll x) {return (x==0?-1:__builtin_ctzll(x));}
#define int long long
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<pii> vp;
typedef tuple<int,int,int> tiii;
int read() {
int x=0,w=1; char c=getchar();
while(!isdigit(c)) {if(c=='-') w=-1; c=getchar();}
while(isdigit(c)) {x=x*10+(c-'0'); c=getchar();}
return x*w;
}
const int N=1e5+5,B=64;
int n,p[4][N],q[4][N],ans;
bitset<N> b[4][N/32];
signed main() {
n=read();
rep(i,1,n) rep(j,0,3) q[j][p[j][i]=read()]=i;
rep(x,0,3) {
rep(i,1,n) b[x][(p[x][i]-1)/B+1][i]=1;
rep(i,1,n/B+1) b[x][i]|=b[x][i-1];
}
rep(i,1,n) {
qwq.set();
rep(x,0,3) {
tmp=b[x][(p[x][i]-1)/B];
int l=(p[x][i]-1)/B*B+1, r=p[x][i];
rep(j,l,r-1) tmp[q[x][j]]=1;
assert(tmp.count()==p[x][i]-1);
qwq&=tmp;
}
ans+=qwq.count();
}
printf("%lld\n",ans);
return 0;
}