#include <bits/stdc++.h>
using namespace std;
const int maxn = 5010;
const int maxnum = 1000000000;
bool done[maxn + 1];
int xl[maxn + 1], level[maxn + 1];
int dist[maxn + 1][maxn + 1];
vector<int> g[maxn + 1];
vector<int> fg[maxn + 1];
int color[maxn + 1], cycle[maxn + 1], sccCycle[maxn + 1], sccSize[maxn + 1];
bool issink[maxn + 1];
int result, colortop, xltop;
int n, m;
void init() {
  int i, x, y;
  scanf("%d%d", &n, &m);
  for (i = 1; i <= m; ++i) {
    scanf("%d%d", &x, &y);
    g[x].push_back(y);
    fg[y].push_back(x);
  }
}
void bfs(int p) {
  int i, j, x, head, tail;
  for (j = 1; j <= n; ++j) done[j] = false;
  head = 0;
  tail = 1;
  level[p] = 0;
  done[p] = true;
  xl[1] = p;
  while (head < tail) {
    i = xl[++head];
    for (j = 0; j < g[i].size(); ++j) {
      x = g[i][j];
      if (!done[x]) {
        level[x] = level[i] + 1;
        done[x] = true;
        xl[++tail] = x;
      }
    }
  }
}
void calc_cycle() {
  int i, j;
  for (i = 1; i <= n; ++i) {
    bfs(i);
    for (j = 1; j <= n; ++j)
      if (done[j])
        dist[i][j] = level[j];
      else
        dist[i][j] = maxnum;
  }
  for (i = 1; i <= n; ++i) {
    cycle[i] = maxnum;
    for (j = 1; j <= n; ++j)
      if (j != i && dist[i][j] < maxnum && dist[j][i] < maxnum &&
          dist[i][j] + dist[j][i] < cycle[i]) {
        cycle[i] = dist[i][j] + dist[j][i];
      }
  }
}
void dfs(int p) {
  done[p] = true;
  for (int i = 0; i < g[p].size(); ++i)
    if (!done[g[p][i]]) dfs(g[p][i]);
  xl[++xltop] = p;
}
void dfs2(int p) {
  color[p] = colortop;
  done[p] = true;
  for (int i = 0; i < fg[p].size(); ++i)
    if (!done[fg[p][i]]) dfs2(fg[p][i]);
}
void calc_color() {
  int i, j;
  xltop = 0;
  for (i = 1; i <= n; ++i) done[i] = false;
  for (i = 1; i <= n; ++i)
    if (!done[i]) dfs(i);
  for (i = 1; i <= n; ++i) done[i] = false;
  colortop = 0;
  for (i = n; i >= 1; --i)
    if (!done[xl[i]]) {
      ++colortop;
      dfs2(xl[i]);
    }
}
void calc_result() {
  int i, j, cx, cy;
  for (i = 1; i <= colortop; ++i) {
    issink[i] = true;
    sccSize[i] = 0;
  }
  for (i = 1; i <= n; ++i) {
    ++sccSize[color[i]];
    for (j = 0; j < g[i].size(); ++j) {
      cx = color[i];
      cy = color[g[i][j]];
      if (cx != cy) issink[cx] = false;
    }
  }
  for (i = 1; i <= colortop; ++i) sccCycle[i] = maxnum;
  for (i = 1; i <= n; ++i)
    if (issink[color[i]] && cycle[i] < sccCycle[color[i]])
      sccCycle[color[i]] = cycle[i];
  result = n;
  for (i = 1; i <= colortop; ++i)
    if (issink[i] && sccSize[i] > 1) result += 1 + 998 * sccCycle[i];
}
void work() {
  calc_cycle();
  calc_color();
  calc_result();
}
void output() { printf("%d\n", result); }
int main() {
  init();
  work();
  output();
  return 0;
}
