#include <bits/stdc++.h>
using namespace std;
const long long inf = 1e18;
const long long mod = 1e9 + 7;
const long long maxn = 5e3 + 10, maxm = 400, mlg = (1 << 18) + 10;
vector<long long> ts, nei[maxn][2];
long long mark1[maxn], mark2[maxn], mark3[maxn];
set<long long> se;
long long h[maxn], mo[maxn], cnt, cnt_scc, t_len, n, m;
queue<long long> qu;
void dfs1(long long u) {
  mark1[u] = 1;
  for (auto v : nei[u][1]) {
    if (!mark1[v]) {
      dfs1(v);
    }
  }
  ts.push_back(u);
}
void dfs2(long long u) {
  mark2[u] = 1;
  mo[u] = cnt;
  se.insert(u);
  for (auto v : nei[u][0]) {
    if (!mark2[v]) {
      dfs2(v);
    }
  }
}
long long girth(set<long long> se) {
  long long mn = inf;
  for (auto u : se) {
    for (int i = 1; i <= n; i++) {
      h[i] = inf;
      mark3[i] = 0;
    }
    qu.push(u);
    h[u] = 1;
    mark3[u] = 1;
    while (!qu.empty()) {
      long long v = qu.front();
      qu.pop();
      for (auto w : nei[v][1]) {
        if (!mark3[w]) {
          qu.push(w);
          mark3[w] = 1;
          h[w] = h[v] + 1;
        } else if (w == u) {
          mn = min(mn, h[v]);
        }
      }
    }
  }
  return mn;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    long long u, v;
    cin >> u >> v;
    nei[u][1].push_back(v);
    nei[v][0].push_back(u);
  }
  for (int i = 1; i <= n; i++) {
    if (!mark1[i]) {
      dfs1(i);
    }
  }
  while (!ts.empty()) {
    if (!mark2[ts.back()]) {
      se.clear();
      bool can = true;
      cnt++;
      dfs2(ts.back());
      for (auto u : se) {
        for (auto v : nei[u][1]) {
          if (mo[u] != mo[v]) {
            can = false;
          }
        }
      }
      if (can) {
        long long tmp = girth(se);
        if (tmp != inf) {
          cnt_scc++;
          t_len += tmp;
        }
      }
      ts.pop_back();
    } else {
      ts.pop_back();
    }
  }
  cout << n + cnt_scc + 998 * t_len << endl;
}
