#include <bits/stdc++.h>
#define ar array
#define ll long long
#define endl '\n'
using namespace std;

const int MAX_N = 1e5 + 1;
const ll MOD = 1e9 + 7;
const ll INF = 1e9;

int MAX = INT_MAX;
long long LMAX = LONG_LONG_MAX;

vector<vector<int>> a;
bool check[2000];

void dfs(int c) { 
    if(check[c]) return;
    check[c] = true;
    for(auto it:a[c]) { 
        dfs(it);
    }
}

void solve() {
    int n, m;
    cin >> n >> m;
    a.resize(n);
    for(int i=0; i<m; i++) { 
        int x,y;
        cin >> x >> y;
        a[x-1].push_back(y-1);
    }
    int ans=0; 
    for(int i=0; i<n; i++) { 
        for(int j=0; j<n; j++) check[j] = false; 
        dfs(i);
        for(int j=0; j<n; j++) if(check[j]) ans++;
    }
    cout << ans << endl;
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int tc = 1;
    // cin >> tc;
    while(tc--) {
        // cout << "Case #" << t  << ": ";
        solve();
    }
}
#include <bits/stdc++.h>
using namespace std;

int main(){
   int n;
   cin >> n;
   vector<tuple<int,int,int>> a;
   int b[4][2] = {{0,0},{0,-1},{1,0},{1,-1}};
   for(int i = 0; i< n;i++){
      int type;
      cin >> type;
      int inp1,inp2;
      cin >> inp1 >> inp2;
      a.push_back(make_tuple(type,inp1,inp2));
   }

   int cnt = 0;
   for(int i = 0;i < n;i++){
      for(int j = i + 1;j < n;j++){
         if(get<2>(a.at(i)) < get<1>(a.at(j))
         || get<2>(a.at(j)) < get<1>(a.at(i))
         || (get<2>(a.at(i)) == get<1>(a.at(j)) && (get<0>(a.at(i)) == 2 || get<0>(a.at(i)) == 4 || get<0>(a.at(j)) == 3 || get<0>(a.at(j)) == 4))
         || (get<2>(a.at(j)) == get<1>(a.at(i)) && (get<0>(a.at(i)) == 3 || get<0>(a.at(i)) == 4 || get<0>(a.at(j)) == 2 || get<0>(a.at(j)) == 4))
        ){

            continue;
         }
         cnt++;
      }
   }
   cout << cnt;
}