#include <bits/stdc++.h>
using namespace std;
const int inf = 2e9;
const long long Inf = 1e10;
const int P = 1e9 + 7;
const int N = 5005;
inline long long IN() {
  long long x = 0;
  int ch = 0, f = 0;
  for (ch = getchar(); ch != -1 && (ch < 48 || ch > 57); ch = getchar())
    f = (ch == '-');
  for (; ch >= 48 && ch <= 57; ch = getchar())
    x = (x << 1) + (x << 3) + ch - '0';
  return f ? (-x) : x;
}
template <typename T>
inline int chkmin(T &a, const T &b) {
  if (b < a) return a = b, 1;
  return 0;
}
template <typename T>
inline int chkmax(T &a, const T &b) {
  if (b > a) return a = b, 1;
  return 0;
}
void renew(int &x, const int &y) {
  if ((x += y) >= P) x -= P;
}
int Pow(int x, int y, int p) {
  int a = 1;
  for (; y; y >>= 1, x = (long long)x * x % p)
    if (y & 1) a = (long long)a * x % p;
  return a;
}
int ha[N];
int n, m, r, q[N], dis[N][N];
vector<int> e[N];
int main() {
  scanf("%d%d", &n, &m);
  for (int i = (int)(1); i <= (int)(m); i++) {
    int x, y;
    scanf("%d%d", &x, &y);
    e[x].push_back(y);
  }
  for (int s = (int)(1); s <= (int)(n); s++) {
    r = 0;
    for (int i = (int)(0); i < (int)(e[s].size()); i++)
      dis[s][q[++r] = e[s][i]] = 1;
    for (int l = (int)(1); l <= (int)(r); l++) {
      int u = q[l];
      for (int i = (int)(0); i < (int)(e[u].size()); i++) {
        int v = e[u][i];
        if (!dis[s][v]) dis[s][q[++r] = v] = dis[s][u] + 1;
      }
    }
  }
  int ans = 0;
  for (int minv = (int)(1); minv <= (int)(n); minv++) {
    if (ha[minv]) continue;
    if (!dis[minv][minv]) continue;
    int ok = 1;
    for (int i = (int)(1); i <= (int)(n); i++)
      if (dis[minv][i] && !dis[i][minv]) {
        ok = 0;
        break;
      }
    if (ok) {
      int minc = inf;
      for (int i = (int)(1); i <= (int)(n); i++)
        if (dis[minv][i]) {
          ha[i] = 1;
          chkmin(minc, dis[i][i]);
        }
      ans += 998 * minc + 1;
    }
  }
  ans += n;
  printf("%d\n", ans);
  return 0;
}
