#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e3 + 10;
int n, cnt, mnd[maxn], mn, sum, dis[maxn], disr[maxn], m;
vector<int> veci[maxn], rev[maxn], ft, scc[maxn];
bool mark[maxn];
void dfs(int u, vector<int>* g, vector<int>& node) {
  if (mark[u]) return;
  mark[u] = 1;
  for (auto x : g[u]) dfs(x, g, node);
  node.push_back(u);
}
void bfs(int u, vector<int>* g, int* node) {
  mark[u] = 1;
  queue<int> qu;
  qu.push(u);
  while (qu.size()) {
    int x = qu.front();
    qu.pop();
    for (auto y : g[x])
      if (!mark[y]) {
        mark[y] = 1;
        node[y] = node[x] + 1;
        qu.push(y);
      }
  }
}
void fil(int a) {
  for (auto x : scc[a]) mark[x] = 0;
}
int main() {
  ios_base ::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int a, b;
    cin >> a >> b;
    a--, b--;
    veci[a].push_back(b);
    rev[b].push_back(a);
  }
  for (int i = 0; i < n; i++)
    if (!mark[i]) dfs(i, veci, ft);
  fill_n(mark, maxn, 0);
  for (; ft.size(); ft.pop_back()) {
    int u = ft.back();
    if (mark[u]) continue;
    dfs(u, rev, scc[mn]);
    for (auto x : scc[mn]) mnd[x] = mn;
    mn++;
  }
  fill_n(mark, maxn, 0);
  for (int i = 0; i < mn; i++) {
    bool zx = 0;
    for (auto x : scc[i])
      for (auto y : veci[x])
        if (mnd[y] != i) {
          zx = 1;
          break;
        }
    if (!zx) {
      int mini = 1e9 + 8;
      for (auto x : scc[i]) {
        dis[x] = 0, disr[x] = 0;
        fil(i);
        bfs(x, veci, dis);
        fil(i);
        bfs(x, rev, disr);
        for (auto y : scc[i]) {
          if (y == x) continue;
          mini = min(mini, dis[y] + disr[y]);
        }
      }
      if (mini != 1e9 + 8) {
        cnt++;
        sum += mini;
      }
    }
  }
  cout << n + cnt + sum * 998;
}
