#include <bits/stdc++.h>
using namespace std;
const int N = 5000 + 5;
int n, m;
int d[N][N], q[N], p[N], cycle[N];
vector<int> v[N];
int main() {
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int x, y;
    scanf("%d %d", &x, &y);
    v[x].push_back(y);
  }
  memset(d, 31, sizeof(d));
  for (int i = 1; i <= n; i++) {
    int sz = 0;
    q[sz++] = i;
    d[i][i] = 0;
    for (int it = 0; it < sz; it++) {
      int x = q[it];
      for (auto u : v[x]) {
        if (d[i][x] + 1 < d[i][u]) {
          d[i][u] = d[i][x] + 1;
          q[sz++] = u;
        }
      }
    }
  }
  for (int i = 1; i <= n; i++)
    for (int j = i; j >= 1; j--)
      if (d[i][j] < n and d[j][i] < n) p[i] = j;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++)
      if (i != j and d[i][j] < n and p[i] != p[j]) cycle[i] = -1;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++)
      if (i != j and p[i] == p[j])
        if (cycle[p[i]] == 0 or d[i][j] + d[j][i] < cycle[p[i]])
          cycle[p[i]] = d[i][j] + d[j][i];
  int ans = n;
  for (int i = 1; i <= n; i++)
    if (p[i] == i and cycle[i] > 0) ans += 998 * cycle[i] + 1;
  printf("%d\n", ans);
  return 0;
}
