#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  for (; !isdigit(ch); ch = getchar())
    if (ch == '-') f = -1;
  for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0';
  return x * f;
}
const int N = 5005;
struct Edge {
  int to, nxt;
} e[N];
int head[N], dis[N], dfn[N], low[N], bel[N], sk[N], q[N], deg[N];
int Index, En, top, cnt, n, Cir;
bool ins[N];
vector<int> vec[N], T[N];
inline void add_edge(int u, int v) {
  ++En;
  e[En].to = v, e[En].nxt = head[u];
  head[u] = En;
  T[v].push_back(u);
}
void tarjan(int u) {
  dfn[u] = low[u] = ++Index;
  sk[++top] = u, ins[u] = 1;
  for (int i = head[u], v = e[i].to; i; i = e[i].nxt, v = e[i].to) {
    if (!dfn[v])
      tarjan(v), low[u] = min(low[u], low[v]);
    else if (ins[v])
      low[u] = min(low[u], dfn[v]);
  }
  if (low[u] == dfn[u]) {
    ++cnt;
    do {
      bel[sk[top]] = cnt, vec[cnt].push_back(sk[top]), ins[sk[top]] = 0;
      top--;
    } while (sk[top + 1] != u);
  }
}
void find(int x) {
  for (int i = 1; i <= n; ++i) dis[i] = -1;
  int L = 1, R = 0;
  q[++R] = x, dis[x] = 0;
  while (L <= R) {
    int u = q[L++];
    for (int i = head[u], v = e[i].to; i; i = e[i].nxt, v = e[i].to)
      if (dis[v] == -1) dis[v] = dis[u] + 1, q[++R] = v;
  }
  for (int i = 0; i < (int)T[x].size(); ++i)
    if (dis[T[x][i]] != -1) Cir = min(Cir, dis[T[x][i]] + 1);
}
int main() {
  n = read();
  int m = read();
  for (int u, v, i = 1; i <= m; ++i) u = read(), v = read(), add_edge(u, v);
  for (int i = 1; i <= n; ++i)
    if (!dfn[i]) tarjan(i);
  for (int u = 1; u <= n; ++u)
    for (int i = head[u], v = e[i].to; i; i = e[i].nxt, v = e[i].to)
      if (bel[u] != bel[v]) deg[bel[u]]++;
  int res = n;
  for (int i = 1; i <= cnt; ++i)
    if (deg[i] == 0 && vec[i].size() > 1) {
      Cir = n + 1;
      for (int j = 0; j < (int)vec[i].size(); ++j) find(vec[i][j]);
      res += 998 * Cir + 1;
    }
  cout << res;
  return 0;
}
