#include <bits/stdc++.h>
using namespace std;
const int N = 5e3 + 9;
int n, m, k, mark[N], c, o[N], is[N], dis[N];
vector<int> g[N], h[N], t, hv[N];
void dfs(int v) {
  mark[v] = 1;
  for (auto u : g[v])
    if (!mark[u]) dfs(u);
  t.push_back(v), o[v] = t.size();
}
void sfd(int v, int c) {
  mark[v] = c, hv[c].push_back(v);
  for (auto u : h[v])
    if (!mark[u]) sfd(u, c);
}
queue<int> q;
int bfs(int v) {
  int ret = 1e9;
  q.push(v), memset(dis, 0, sizeof dis), dis[v] = 1;
  while (q.size()) {
    int v = q.front();
    q.pop();
    for (auto u : g[v])
      if (!dis[u])
        dis[u] = dis[v] + 1, q.push(u);
      else
        ret = min(ret, dis[v] + dis[u] - 1);
  }
  return ret;
}
int cyc(int c) {
  int ret = 1e9;
  for (auto i : hv[c]) ret = min(ret, bfs(i));
  return ret;
}
int main() {
  cin >> n >> m;
  for (int i = 0, v, u; i < m; i++)
    cin >> v >> u, g[v - 1].push_back(u - 1), h[u - 1].push_back(v - 1);
  for (int i = 0; i < n; i++)
    if (!mark[i]) dfs(i);
  reverse(t.begin(), t.end()), memset(mark, 0, sizeof mark);
  for (auto i : t)
    if (!mark[i]) sfd(i, ++c);
  fill(is, is + N, 1);
  for (int i = 0; i < n; i++)
    for (auto j : g[i])
      if (o[j] < o[i] && mark[j] != mark[i]) is[mark[i]] = 0;
  for (int i = 1; i <= c; i++)
    if (is[i] && hv[i].size() != 1) n = n + 1 + cyc(i) * 998;
  cout << n;
  return 0;
}
