#include <bits/stdc++.h>
using namespace std;
const int N = 5010;
vector<int> g[N], gt[N];
stack<int> st;
bool done[N];
int dist[N];
vector<vector<int>> comp;
int myComp[N];
void scc1(int a) {
  done[a] = true;
  for (auto x : g[a]) {
    if (!done[x]) scc1(x);
  }
  st.push(a);
}
void scc2(int a) {
  done[a] = true;
  comp.back().push_back(a);
  myComp[a] = comp.size() - 1;
  for (auto x : gt[a]) {
    if (!done[x]) scc2(x);
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < (m); i++) {
    int a, b;
    cin >> a >> b;
    a--, b--;
    g[a].push_back(b);
    gt[b].push_back(a);
  }
  for (int i = 0; i < (n); i++) {
    if (!done[i]) {
      scc1(i);
    }
  }
  memset(done, 0, sizeof(done));
  while (!st.empty()) {
    int i = st.top();
    st.pop();
    if (done[i]) continue;
    comp.push_back(vector<int>());
    scc2(i);
  }
  memset(done, 0, sizeof(done));
  int res = n;
  for (int i = 0; i < (comp.size()); i++) {
    if (comp[i].size() == 1) continue;
    bool easy = false;
    for (auto x : comp[i]) {
      assert(myComp[x] == myComp[comp[i][0]]);
      for (auto y : g[x]) {
        if (myComp[y] != myComp[x]) {
          easy = true;
          break;
        }
      }
      if (easy) break;
    }
    if (easy) continue;
    int bestcyc = N;
    for (auto fst : comp[i]) {
      memset(dist, -1, sizeof(dist));
      queue<int> q;
      q.push(fst);
      dist[fst] = 0;
      int cyclen = -1;
      while (!q.empty()) {
        int cur = q.front();
        q.pop();
        for (auto x : g[cur]) {
          if (x == fst) {
            cyclen = dist[cur] + 1;
            break;
          }
          if (dist[x] != -1) continue;
          dist[x] = dist[cur] + 1;
          q.push(x);
        }
        if (cyclen != -1) break;
      }
      assert(cyclen != -1);
      bestcyc = min(bestcyc, cyclen);
    }
    res += 998 * bestcyc + 1;
  }
  cout << res << endl;
  return 0;
}
