#include <bits/stdc++.h>
using namespace std;
int n, m, s[5010], e[5010];
vector<int> v[5010];
int dfn[5010], low[5010], tim, stk[5010], top;
bool vis[5010];
vector<int> scc[5010];
int scccnt = 0, cnt[5010], bel[5010];
void dfs(int np) {
  dfn[np] = low[np] = ++tim;
  vis[np] = 1;
  stk[++top] = np;
  for (int i = 0; i < v[np].size(); i++) {
    int x = v[np][i];
    if (!dfn[x]) {
      dfs(x);
      low[np] = min(low[np], low[x]);
    } else if (vis[x])
      low[np] = min(low[np], dfn[x]);
  }
  if (low[np] == dfn[np]) {
    int tmp;
    ++scccnt;
    while ((tmp = stk[top--])) {
      vis[tmp] = 0;
      scc[scccnt].push_back(tmp);
      bel[tmp] = scccnt;
      if (tmp == np) break;
    }
  }
}
bool ok[5010], instk[5010];
int dep[5010];
inline int getcycle(int st) {
  static queue<int> q;
  while (!q.empty()) q.pop();
  q.push(st);
  memset(dep, 0, sizeof(dep));
  dep[st] = 1;
  while (!q.empty()) {
    int fr = q.front();
    q.pop();
    for (int &x : v[fr]) {
      if (!ok[x]) continue;
      if (!dep[x]) {
        dep[x] = dep[fr] + 1;
        q.push(x);
      } else if (x == st)
        return dep[fr];
    }
  }
  return -1;
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1, ti, tj; i <= m; i++) {
    scanf("%d%d", &ti, &tj);
    s[i] = ti;
    e[i] = tj;
    v[ti].push_back(tj);
  }
  for (int i = 1; i <= n; i++)
    if (!dfn[i]) dfs(i);
  for (int i = 1; i <= m; i++) {
    if (bel[s[i]] != bel[e[i]]) cnt[bel[s[i]]]++;
  }
  int cntcycle = 0, sizcycle = 0;
  for (int i = 1; i <= scccnt; i++) {
    if (!cnt[i]) {
      if (scc[i].size() == 1) continue;
      cntcycle++;
      for (auto &x : scc[i]) ok[x] = 1;
      int c = 0x3f3f3f3f;
      for (auto &x : scc[i]) c = min(c, getcycle(x));
      sizcycle += c;
      for (auto &x : scc[i]) ok[x] = 0;
    }
  }
  printf("%d\n", n + sizcycle * 998 + cntcycle);
  return 0;
}
