#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> g[5000], rev[5000];
bool used[5000];
vector<int> ord;
bool curcm[5000];
vector<int> cm;
void dfs1(int v) {
  used[v] = true;
  for (int to : g[v])
    if (!used[to]) {
      dfs1(to);
    }
  ord.push_back(v);
}
void dfs2(int v) {
  used[v] = true;
  cm.push_back(v);
  curcm[v] = true;
  for (int to : rev[v])
    if (!used[to]) {
      dfs2(to);
    }
}
int dist[5000][5000];
int q[5000];
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < (int)(m); ++i) {
    int from, to;
    scanf("%d%d", &from, &to), --from, --to;
    g[from].push_back(to);
    rev[to].push_back(from);
  }
  memset(dist, -1, sizeof dist);
  for (int i = 0; i < (int)(n); ++i) {
    int(&d)[5000] = dist[i];
    d[i] = 0;
    q[0] = i;
    for (int qh = 0, qt = 1; qh < qt; ++qh) {
      int v = q[qh];
      for (int to : g[v])
        if (d[to] == -1) {
          d[to] = d[v] + 1;
          q[qt++] = to;
        }
    }
  }
  for (int i = 0; i < (int)(n); ++i) used[i] = false;
  for (int i = 0; i < (int)(n); ++i)
    if (!used[i]) {
      dfs1(i);
    }
  reverse(ord.begin(), ord.end());
  for (int i = 0; i < (int)(n); ++i) used[i] = false;
  int ans = n;
  for (int v : ord)
    if (!used[v]) {
      cm.clear();
      for (int i = 0; i < (int)(n); ++i) curcm[i] = false;
      dfs2(v);
      bool ok = false;
      for (int x : cm) {
        for (int y : g[x])
          if (!curcm[y]) {
            ok = true;
            break;
          }
        if (ok) break;
      }
      if (!ok && (int)cm.size() > 1) {
        ++ans;
        int z = 12341234;
        for (int x : cm)
          for (int y : cm) {
            if (y == x) break;
            z = min(z, dist[x][y] + dist[y][x]);
          }
        ans += z * 998;
      }
    }
  printf("%d\n", ans);
  return 0;
}
