#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
long long powmod(long long a, long long b) {
  long long res = 1;
  a %= mod;
  assert(b >= 0);
  for (; b; b >>= 1) {
    if (b & 1) res = res * a % mod;
    a = a * a % mod;
  }
  return res;
}
const int N = 5010;
int dfn[N], low[N], ins[N], st[N], bel[N], dis[N], vis[N];
int ind, top, n, m, u, v, cnt, maxc;
vector<int> vec[N], e[N], f[N];
queue<int> q;
vector<pair<int, int> > E;
void tarjan(int u) {
  dfn[u] = low[u] = ++ind;
  ins[u] = 1;
  st[++top] = u;
  for (int i = 0; i < ((int)(e[u]).size()); i++) {
    int v = e[u][i];
    if (!dfn[v])
      tarjan(v), low[u] = min(low[u], low[v]);
    else if (ins[v])
      low[u] = min(low[u], low[v]);
  }
  if (dfn[u] == low[u]) {
    ++cnt;
    while (1) {
      bel[st[top]] = cnt;
      vec[cnt].push_back(st[top]);
      ins[st[top]] = 0;
      if (st[top--] == u) break;
    }
  }
}
void find(int u) {
  for (int i = 1; i < n + 1; i++) vis[i] = 0, dis[i] = n + 1;
  vis[u] = 1;
  q.push(u);
  dis[u] = 0;
  while (!q.empty()) {
    int v = q.front();
    q.pop();
    for (auto w : e[v])
      if (!vis[w]) {
        vis[w] = 1;
        dis[w] = dis[v] + 1;
        q.push(w);
      }
  }
  for (int i = 1; i < n + 1; i++)
    for (auto v : e[i])
      if (v == u) {
        maxc = min(maxc, dis[i] + 1);
      }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < m; i++) {
    scanf("%d%d", &u, &v);
    e[u].push_back(v);
    E.push_back(make_pair(u, v));
  }
  for (int i = 1; i < n + 1; i++)
    if (!dfn[i]) tarjan(i);
  for (int i = 0; i < m; i++) {
    int u = E[i].first, v = E[i].second;
    if (bel[u] != bel[v]) {
      f[bel[u]].push_back(bel[v]);
    }
  }
  int ret = n;
  for (int i = 1; i < cnt + 1; i++)
    if (((int)(f[i]).size()) == 0) {
      if (((int)(vec[i]).size()) == 1) continue;
      maxc = n;
      for (auto u : vec[i]) find(u);
      ret += 998 * maxc + 1;
    }
  printf("%d\n", ret);
}
