#include <bits/stdc++.h>
using namespace std;
int n, m, u, v, s, to[5010], ne[5010], pre[5010], cnt, dfn[5010], low[5010],
    len, f[5010], ss, q[5010], w[5010], d[5010], dis[5010];
bool us[5010];
void add(int u, int v) {
  to[++s] = v;
  ne[s] = pre[u];
  pre[u] = s;
}
void dfs(int k) {
  dfn[k] = low[k] = ++cnt;
  f[++len] = k;
  us[k] = true;
  for (int i = pre[k]; i; i = ne[i]) {
    int x = to[i];
    if (!dfn[x]) {
      dfs(x);
      low[k] = min(low[k], low[x]);
    } else if (us[x])
      low[k] = min(low[k], low[x]);
  }
  if (dfn[k] == low[k]) {
    ss++;
    while (f[len] != k) us[f[len]] = false, w[ss]++, q[f[len--]] = ss;
    us[k] = false;
    w[ss]++;
    q[f[len--]] = ss;
  }
}
int bfs(int k, int u) {
  int h = 0, t = 1;
  f[1] = u;
  memset(dis, 0, sizeof(dis));
  while (h < t) {
    int x = f[++h];
    for (int i = pre[x]; i; i = ne[i])
      if (q[to[i]] == k && !dis[to[i]]) {
        int o = to[i];
        dis[o] = dis[x] + 1;
        if (o == u) return dis[o];
        f[++t] = o;
      }
  }
}
int get(int k) {
  if (w[k] == 1) return 0;
  int mn = 1e9;
  for (int i = 1; i <= n; i++)
    if (q[i] == k) mn = min(mn, bfs(k, i));
  return 1 + 998 * mn;
}
int main() {
  cin >> n >> m;
  while (m--) scanf("%d%d", &u, &v), add(u, v);
  for (int i = 1; i <= n; i++)
    if (!dfn[i]) dfs(i);
  for (int i = 1; i <= n; i++)
    for (int j = pre[i]; j; j = ne[j])
      if (q[i] != q[to[j]]) d[q[i]]++;
  int ans = n;
  for (int i = 1; i <= ss; i++)
    if (!d[i]) ans += get(i);
  cout << ans;
}
