#include <bits/stdc++.h>
using namespace std;
const int limite = 5005;
int n, m;
vector<int> g[limite];
int norden = 0;
int visto[limite];
int dist[limite][limite];
int numaccesibles[limite];
int lista[limite];
int nc;
int c[limite];
bool compara(int u, int v) { return numaccesibles[u] < numaccesibles[v]; }
void calculadist(int uini) {
  int(&dis)[limite] = dist[uini];
  for (int i = 1; i <= n; i++) dis[i] = n;
  dis[uini] = 0;
  numaccesibles[uini] = 1;
  queue<int> q;
  q.push(uini);
  while (not q.empty()) {
    int u = q.front();
    q.pop();
    vector<int> &ar = g[u];
    for (int i = 0; i < int(ar.size()); i++) {
      int v = ar[i];
      if (dis[v] == n) {
        dis[v] = dis[u] + 1;
        q.push(v);
        numaccesibles[uini]++;
      }
    }
  }
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int u, v;
    cin >> u >> v;
    g[u].push_back(v);
  }
  for (int u = 1; u <= n; u++) {
    calculadist(u);
    lista[u - 1] = u;
  }
  sort(lista, lista + n, compara);
  int sol = 0;
  for (int i = 0; i < n; i++) {
    int u = lista[i];
    if (visto[u]) continue;
    bool error = false;
    for (int v = 1; v <= n and not error; v++)
      error = dist[u][v] < n and visto[v];
    if (not error) {
      if (numaccesibles[u] == 1) {
        sol++;
        visto[u] = 1;
      } else {
        nc = 0;
        for (int v = 1; v <= n; v++) {
          if (dist[u][v] < n) {
            c[nc++] = v;
            visto[v] = 1;
          }
        }
        int minimo = n + n;
        for (int i1 = 0; i1 < nc; i1++)
          for (int i2 = i1 + 1; i2 < nc; i2++)
            minimo = min(minimo, dist[c[i1]][c[i2]] + dist[c[i2]][c[i1]]);
        sol += minimo * 999 + 1 + nc - minimo;
      }
    } else {
      for (int v = 1; v <= n; v++) {
        if (dist[u][v] < n and not visto[v]) {
          sol++;
          visto[v] = 1;
        }
      }
    }
  }
  cout << sol << endl;
}
