#include <bits/stdc++.h>
using namespace std;
vector<int> g[5002];
int from[5002];
int to[5002];
bool visited_parcours[5002];
bool onstack[5002];
int lowlink[5002];
int ind[5002];
int indexmax;
stack<int> pile;
int sccindex;
int scc[5002];
int scc_size[5002];
vector<int> scclist[5002];
void tarjan(int v) {
  ind[v] = indexmax;
  lowlink[v] = indexmax;
  indexmax++;
  pile.push(v);
  onstack[v] = true;
  for (auto w : g[v]) {
    if (ind[w] < 0) {
      tarjan(w);
      lowlink[v] = min(lowlink[v], lowlink[w]);
    } else if (onstack[w])
      lowlink[v] = min(lowlink[v], ind[w]);
  }
  if (lowlink[v] == ind[v]) {
    int w = -1;
    while (w != v) {
      w = pile.top();
      pile.pop();
      onstack[w] = false;
      scc[w] = sccindex;
      scc_size[sccindex]++;
      scclist[sccindex].push_back(w);
    }
    sccindex++;
  }
}
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 0; i < m; i++) {
    int u, v;
    scanf("%d%d", &u, &v);
    u--;
    v--;
    from[i] = u;
    to[i] = v;
    g[u].push_back(v);
  }
  for (int i = 0; i < n; i++) ind[i] = -1;
  for (int i = 0; i < n; i++)
    if (ind[i] < 0) tarjan(i);
  for (int i = 0; i < m; i++) {
    if (scc[from[i]] != scc[to[i]]) {
      scc_size[scc[from[i]]] = 0;
    }
  }
  int ncycles = 0;
  int sizecycles = 0;
  for (int i = 0; i < sccindex; i++) {
    if (scc_size[i] >= 3) {
      int bestsize = 2 * 5002;
      for (auto u : scclist[i]) {
        for (int v = 0; v < n; v++) visited_parcours[v] = false;
        queue<pair<int, int> > bfs;
        for (auto w : g[u]) bfs.push(make_pair(w, 1));
        while (bfs.front().first != u) {
          int cur = bfs.front().first;
          int dist = bfs.front().second;
          bfs.pop();
          visited_parcours[cur] = true;
          for (auto w : g[cur])
            if (!visited_parcours[w]) bfs.push(make_pair(w, dist + 1));
          assert(!bfs.empty());
        }
        bestsize = min(bestsize, bfs.front().second);
      }
      ncycles++;
      sizecycles += bestsize;
    }
  }
  printf("%d\n", ncycles + 998 * sizecycles + n);
  return 0;
}
