#include <bits/stdc++.h>
using namespace std;
int n, m, i, x, y, cnt;
vector<int> to[5016], from[5016];
vector<vector<int> > comp;
vector<int> aux;
bool us[5016];
stack<int> S;
int belong[5016];
bool leaf[5016];
queue<int> Q;
int dist[5016];
int ans;
void dfs_to(int node) {
  us[node] = true;
  for (auto e : to[node])
    if (!us[e]) dfs_to(e);
  S.push(node);
}
void dfs_from(int node) {
  us[node] = true;
  belong[node] = cnt;
  aux.push_back(node);
  for (auto e : from[node])
    if (!us[e]) dfs_from(e);
}
int small_cycle(int id) {
  int i;
  int ans = comp[id].size();
  int act;
  aux = comp[id];
  for (int base : aux) {
    act = 2000000000;
    for (int e : aux) dist[e] = 2000000000;
    dist[base] = 0;
    Q.push(base);
    while (!Q.empty()) {
      int node = Q.front();
      Q.pop();
      for (auto e : to[node]) {
        if (e == base) act = min(act, dist[node] + 1);
        if (dist[e] != 2000000000) continue;
        dist[e] = dist[node] + 1;
        Q.push(e);
      }
    }
    ans = min(ans, act);
  }
  return ans * 999 + 1 + aux.size() - ans;
}
int main() {
  scanf("%d%d", &n, &m);
  for (i = 1; i <= m; i++) {
    scanf("%d%d", &x, &y);
    to[x].push_back(y);
    from[y].push_back(x);
  }
  for (i = 1; i <= n; i++)
    if (!us[i]) dfs_to(i);
  memset(us, 0, sizeof(us));
  while (!S.empty()) {
    int node = S.top();
    S.pop();
    if (us[node]) continue;
    aux.clear();
    dfs_from(node);
    comp.push_back(aux);
    cnt++;
  }
  for (i = 0; i < comp.size(); i++) leaf[i] = true;
  for (i = 1; i <= n; i++)
    for (int e : to[i])
      if (belong[i] != belong[e]) leaf[belong[i]] = false;
  for (i = 0; i < comp.size(); i++) {
    if (!leaf[i] || comp[i].size() == 1)
      ans += comp[i].size();
    else
      ans += small_cycle(i);
  }
  printf("%d", ans);
  return 0;
}
