#include <bits/stdc++.h>
using namespace std;
const int inf = 1000000000;
struct edge {
  int to, next;
} e[5005];
int n, m, num, head[5005], d[5005][5005], belong[5005], s[5005], top, dfn[5005],
    low[5005], scc, ans, circle[5005];
bool ok[5005];
queue<int> q;
inline void insert(int u, int v) {
  e[++num].to = v;
  e[num].next = head[u];
  head[u] = num;
}
inline void bfs(int s) {
  q.push(s);
  for (int i = 1; i <= n; i++)
    if (s != i) d[s][i] = inf;
  while (!q.empty()) {
    int now = q.front();
    q.pop();
    for (int i = head[now]; i; i = e[i].next)
      if (d[s][e[i].to] == inf) {
        d[s][e[i].to] = d[s][now] + 1;
        q.push(e[i].to);
      }
  }
}
void dfs(int now) {
  dfn[now] = low[now] = ++num;
  s[++top] = now;
  ok[now] = true;
  for (int i = head[now]; i; i = e[i].next)
    if (!ok[e[i].to]) {
      dfs(e[i].to);
      low[now] = min(low[now], low[e[i].to]);
    } else if (!belong[e[i].to])
      low[now] = min(low[now], dfn[e[i].to]);
  if (dfn[now] == low[now]) {
    belong[now] = ++scc;
    while (s[top] != now) {
      belong[s[top]] = scc;
      top--;
    }
    top--;
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; i++) {
    int u, v;
    scanf("%d%d", &u, &v);
    insert(u, v);
  }
  for (int i = 1; i <= n; i++) bfs(i);
  num = 0;
  for (int i = 1; i <= n; i++)
    if (!ok[i]) dfs(i);
  memset(ok, false, sizeof(ok));
  for (int i = 1; i <= scc; i++) circle[i] = inf;
  for (int u = 1; u <= n; u++)
    for (int i = head[u]; i; i = e[i].next) {
      int v = e[i].to;
      if (belong[u] == belong[v])
        circle[belong[u]] = min(circle[belong[u]], d[v][u] + 1);
      else
        ok[belong[u]] = true;
    }
  ans = n;
  for (int i = 1; i <= scc; i++)
    if (!ok[i] && circle[i] != inf) ans += 998 * circle[i] + 1;
  printf("%d\n", ans);
  return 0;
}
