#include <bits/stdc++.h>
using namespace std;
vector<vector<int> > al, dist;
int n, m;
bool done[5000];
vector<int> bfs(const vector<vector<int> >& al, int s) {
  queue<int> q;
  vector<int> dist(al.size(), INT_MAX);
  dist[s] = 0;
  q.push(s);
  while (!q.empty()) {
    int i = q.front();
    q.pop();
    for (int j : al[i])
      if (dist[j] == INT_MAX) {
        dist[j] = dist[i] + 1;
        q.push(j);
      }
  }
  return dist;
}
int main() {
  ios::sync_with_stdio(0);
  cin >> n >> m;
  int r = n;
  al.resize(n);
  dist.resize(n);
  int i, j;
  for (int c = 0; c < m; c++) {
    cin >> i >> j;
    i--;
    j--;
    al[i].push_back(j);
  }
  for (int s = 0; s < n; s++) dist[s] = bfs(al, s);
  for (int i = 0; i < n; i++)
    if (!done[i]) {
      vector<int> comp{i};
      done[i] = 1;
      bool outgo = 0;
      for (int j = 0; j < n; j++)
        if (dist[i][j] != INT_MAX && i != j) {
          if (dist[j][i] != INT_MAX) {
            comp.push_back(j);
            done[j] = 1;
          } else
            outgo = 1;
        }
      if (!outgo && comp.size() > 1) {
        int m = INT_MAX;
        for (int c = 0; c < comp.size(); c++)
          for (int d = 0; d < comp.size(); d++)
            if (c != d)
              m = min(m, dist[comp[c]][comp[d]] + dist[comp[d]][comp[c]]);
        r += 998 * m + 1;
      }
    }
  cout << r << '\n';
}
