#include <bits/stdc++.h>
int n, m;
std::vector<std::vector<int> > g, grev;
std::vector<std::vector<int> > gsc;
std::vector<std::vector<int> > inside;
std::vector<int> sc;
int fre;
std::vector<bool> vis;
const int INF = 1000000000;
std::vector<int> topo;
void dfs(int v) {
  vis[v] = true;
  for (auto& ch : (g[v]))
    if (!vis[ch]) {
      dfs(ch);
    }
  topo.push_back(v);
}
void dfs2(int v) {
  inside[fre].push_back(v);
  sc[v] = fre;
  for (auto& ch : (grev[v])) {
    if (sc[ch] != -1) {
      if (sc[ch] != sc[v]) gsc[sc[ch]].push_back(sc[v]);
    } else {
      dfs2(ch);
    }
  }
}
int cyc(int s) {
  std::queue<int> que;
  std::vector<int> dist(n, INF);
  dist[s] = 0;
  que.push(s);
  while (((int)(que).size())) {
    int v = que.front();
    que.pop();
    for (auto& ch : (g[v])) {
      if (ch == s) return dist[v] + 1;
      if (dist[ch] == INF) {
        dist[ch] = dist[v] + 1;
        que.push(ch);
      }
    }
  }
  assert(false);
}
void solve() {
  vis = std::vector<bool>(n);
  topo = std::vector<int>();
  for (int i = 0; i < (n); ++i)
    if (!vis[i]) dfs(i);
  std::reverse(topo.begin(), topo.end());
  fre = 0;
  gsc = std::vector<std::vector<int> >();
  sc = std::vector<int>(n, -1);
  for (auto& i : (topo))
    if (sc[i] == -1) {
      gsc.emplace_back();
      inside.emplace_back();
      dfs2(i);
      fre++;
    }
  int ans = n;
  for (int i = 0; i < (fre); ++i) {
    if (((int)(gsc[i]).size()) == 0) {
      if (((int)(inside[i]).size()) == 1) continue;
      int minsize = INF;
      for (auto& j : (inside[i])) {
        minsize = std::min(minsize, cyc(j));
      }
      ans += 998 * minsize + 1;
    }
  }
  std::cout << ans << "\n";
}
int main() {
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(0);
  std::cin >> n >> m;
  g.resize(n);
  grev.resize(n);
  for (int i = 0; i < (m); ++i) {
    int a, b;
    std::cin >> a >> b;
    a--;
    b--;
    g[a].push_back(b);
    grev[b].push_back(a);
  }
  solve();
  return 0;
}
