#include <bits/stdc++.h>
using namespace std;
const int MX = 5e3;
int n;
vector<int> adj[MX], Radj[MX];
vector<int> post;
bool Mark[MX];
void dfs(int v) {
  Mark[v] = true;
  for (int i = 0; i < adj[v].size(); i++) {
    int u = adj[v][i];
    if (Mark[u] == false) dfs(u);
  }
  post.push_back(v);
}
int compsize;
int ID[MX];
vector<int> comps[MX];
void RevDfs(int v) {
  ID[v] = compsize;
  comps[compsize].push_back(v);
  Mark[v] = true;
  for (int i = 0; i < Radj[v].size(); i++) {
    int u = Radj[v][i];
    if (Mark[u] == false) RevDfs(u);
  }
}
void findSCC() {
  for (int i = 0; i < n; i++)
    if (Mark[i] == false) dfs(i);
  fill_n(Mark, n, false);
  while (post.size() != 0) {
    int v = post[post.size() - 1];
    post.pop_back();
    if (Mark[v] == false) {
      RevDfs(v);
      compsize++;
    }
  }
}
vector<int> Q;
int Dis[MX];
int MinCycle;
int bfs(int root) {
  fill_n(Mark, n, false);
  fill_n(Dis, n, false);
  Q.clear();
  int l = 0, r = 0;
  Mark[root] = true;
  Q.push_back(root);
  r++;
  while (l < r) {
    int v = Q[l++];
    for (int i = 0; i < adj[v].size(); i++) {
      int u = adj[v][i];
      if (Mark[u] == false) {
        Mark[u] = true;
        Dis[u] = Dis[v] + 1;
        Q.push_back(u);
        r++;
      } else if (u == root) {
        return Dis[v] + 1;
      }
    }
  }
}
int m;
int Ans;
bool con[MX];
int main() {
  cin >> n >> m;
  int N = n;
  for (int i = 0; i < m; i++) {
    int x, y;
    cin >> x >> y;
    x--;
    y--;
    adj[x].push_back(y);
    Radj[y].push_back(x);
  }
  findSCC();
  fill_n(Mark, n, false);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < adj[i].size(); j++) {
      int u = adj[i][j];
      if (ID[i] != ID[u]) con[ID[i]] = true;
    }
  for (int i = 0; i < compsize; i++)
    if (comps[i].size() > 1 && con[i] == false) {
      int MinCycle = MX;
      for (int j = 0; j < comps[i].size(); j++) {
        int root = comps[i][j];
        MinCycle = min(MinCycle, bfs(root));
      }
      Ans += MinCycle;
      N++;
    }
  Ans = Ans * 998 + N;
  cout << Ans;
  return 0;
}
