#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
const int MAXN = 5000;
const int MAXM = 5000;
int ng, mg;
int ghead[MAXN], gnxt[MAXM], gto[MAXM];
int nc, nt;
int c[MAXN], t[MAXN], tmn[MAXN];
int stck[MAXN], nstck;
bool cleaf[MAXN];
int chead[MAXN], cnxt[MAXN];
int d[MAXN];
int q[MAXN], qhead, qtail;
void tarjan(int at, int par) {
  t[at] = tmn[at] = nt++, stck[nstck++] = at;
  for (int x = ghead[at]; x != -1; x = gnxt[x]) {
    int to = gto[x];
    if (to == par) continue;
    if (t[to] == -1) {
      tarjan(to, at);
      if (tmn[to] < tmn[at]) tmn[at] = tmn[to];
    } else if (c[to] == -1) {
      if (t[to] < tmn[at]) tmn[at] = t[to];
    }
  }
  if (tmn[at] >= t[at]) {
    while (c[at] == -1) c[stck[--nstck]] = nc;
    ++nc;
  }
}
int mincyc(int s) {
  for (int x = chead[c[s]]; x != -1; x = cnxt[x]) d[x] = INT_MAX;
  qhead = qtail = 0;
  q[qhead++] = s;
  d[s] = 0;
  while (qtail < qhead) {
    int at = q[qtail++];
    assert(c[at] == c[s]);
    for (int x = ghead[at]; x != -1; x = gnxt[x]) {
      int to = gto[x];
      if (to == s) return d[at] + 1;
      if (d[at] + 1 < d[to]) d[to] = d[at] + 1, q[qhead++] = to;
    }
  }
  assert(false);
  return -1;
}
void run() {
  scanf("%d%d", &ng, &mg);
  for (int i = (0); i < (ng); ++i) ghead[i] = -1;
  for (int i = (0); i < (mg); ++i) {
    int a, b;
    scanf("%d%d", &a, &b);
    --a, --b;
    gnxt[i] = ghead[a];
    ghead[a] = i;
    gto[i] = b;
  }
  for (int i = (0); i < (ng); ++i) t[i] = c[i] = -1;
  nc = 0, nt = 0, nstck = 0;
  for (int i = (0); i < (ng); ++i)
    if (t[i] == -1) tarjan(i, -1);
  for (int i = (0); i < (nc); ++i) cleaf[i] = true;
  for (int i = (0); i < (ng); ++i)
    for (int x = ghead[i]; x != -1; x = gnxt[x])
      if (c[i] != c[gto[x]]) cleaf[c[i]] = false;
  for (int i = (0); i < (nc); ++i) chead[i] = -1;
  for (int i = (0); i < (ng); ++i) cnxt[i] = chead[c[i]], chead[c[i]] = i;
  int ret = ng;
  for (int i = (0); i < (nc); ++i)
    if (cleaf[i]) {
      if (cnxt[chead[i]] == -1) continue;
      int cur = INT_MAX;
      for (int x = chead[i]; x != -1; x = cnxt[x]) {
        int now = mincyc(x);
        if (now < cur) cur = now;
      }
      ret += 998 * cur + 1;
    }
  printf("%d\n", ret);
}
int main() {
  run();
  return 0;
}
