#include <bits/stdc++.h>
using namespace std;
int const MAXN = 5e3 + 8;
int const delta = 1000000007;
vector<int> G[MAXN];
vector<int> GR[MAXN];
vector<int> comp[MAXN];
vector<int> T;
int C[MAXN];
int mark[MAXN];
int dist[MAXN];
int mincycle[MAXN];
int out[MAXN];
int cnt;
void dfs(int v) {
  mark[v] = 1;
  for (int i = 0; i < G[v].size(); i++) {
    if (!mark[G[v][i]]) dfs(G[v][i]);
  }
  T.push_back(v);
  ;
}
void scc(int v) {
  comp[cnt].push_back(v);
  ;
  mark[v] = 2;
  C[v] = cnt;
  for (int i = 0; i < GR[v].size(); i++) {
    if (mark[GR[v][i]] == 1) scc(GR[v][i]);
  }
}
void get(int v) {
  memset(mark, 0, sizeof(mark));
  memset(dist, 0, sizeof(dist));
  vector<int> T;
  T.push_back(v);
  ;
  mincycle[v] = delta;
  int p = 0;
  for (int i = 0; i < T.size(); i++) {
    int u = T[i];
    mark[u] = 1;
    for (int j = 0; j < G[u].size(); j++) {
      if (G[u][j] == v) {
        mincycle[v] = dist[u] + 1;
        p = 1;
        break;
      }
      if (mark[G[u][j]]) continue;
      dist[G[u][j]] = dist[u] + 1;
      mark[G[u][j]] = 1;
      T.push_back(G[u][j]);
      ;
    }
    if (p) break;
  }
  if (mincycle[v] == delta) mincycle[v] = 0;
}
int main() {
  std::ios::sync_with_stdio(0);
  ;
  cin.tie(0);
  cout.tie(0);
  int n, m;
  cin >> n >> m;
  int f, s;
  vector<pair<int, int> > edges;
  for (int i = 0; i < m; i++) {
    cin >> f >> s;
    G[f].push_back(s);
    ;
    GR[s].push_back(f);
    ;
    edges.push_back(make_pair(f, s));
    ;
  }
  for (int i = 1; i <= n; i++) {
    if (!mark[i]) {
      dfs(i);
      while (T.size()) {
        int v = T[T.size() - 1];
        T.pop_back();
        if (mark[v] == 2) {
          continue;
        }
        cnt++;
        scc(v);
      }
    }
  }
  for (int i = 0; i < m; i++) {
    if (C[edges[i].first] != C[edges[i].second]) out[C[edges[i].first]]++;
  }
  int ans = n;
  for (int i = 1; i <= cnt; i++) {
    if (out[i]) continue;
    int temp = delta;
    ans++;
    for (int j = 0; j < comp[i].size(); j++) {
      get(comp[i][j]);
      temp = min(temp, mincycle[comp[i][j]]);
    }
    if (!temp) ans--;
    ans += (998 * temp);
  }
  cout << ans;
  return 0;
}
