#include <bits/stdc++.h>
using namespace std;
int const M = 5e3 + 10, mod = 1e9 + 7, inf = 1e9 + 10;
int mark[M];
vector<int> st, adj[M], adj2[M];
vector<int> mo[M];
bool good[M];
int co[M];
int dp[M][2], a[M], b[M];
int cnt = 0, n, m, q[M], ans[M];
void dfs(int v) {
  mark[v] = 1;
  for (int i = 0; i < adj[v].size(); i++) {
    int u = adj[v][i];
    if (!mark[u]) dfs(u);
  }
  st.push_back(v);
}
void dfsb(int v) {
  mark[v] = cnt;
  co[cnt]++;
  for (int i = 0; i < adj2[v].size(); i++) {
    int u = adj2[v][i];
    if (mark[u] != 0 && mark[u] != cnt) {
      good[mark[u]] = 1;
    } else if (!mark[u])
      dfsb(u);
  }
}
void bfs(int v, int id) {
  for (int i = 1; i <= n; i++) {
    dp[i][id] = -1;
  }
  dp[v][id] = 0;
  int head = 0, tail = 0;
  q[head++] = v;
  while (head > tail) {
    int v = q[tail++];
    int tmp = adj[v].size();
    if (id == 1) tmp = adj2[v].size();
    for (int j = 0; j < tmp; j++) {
      int u;
      if (!id)
        u = adj[v][j];
      else
        u = adj2[v][j];
      if (dp[u][id] == -1) q[head++] = u, dp[u][id] = dp[v][id] + 1;
    }
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  for (int i = 1; i <= m; i++) {
    cin >> a[i] >> b[i];
    adj[a[i]].push_back(b[i]);
    adj2[b[i]].push_back(a[i]);
  }
  for (int i = 1; i <= n; i++) {
    if (!mark[i]) dfs(i);
  }
  reverse(st.begin(), st.end());
  for (int i = 1; i <= n; i++) mark[i] = 0, ans[i] = n;
  for (int i = 0; i < st.size(); i++) {
    if (!mark[st[i]]) ++cnt, dfsb(st[i]);
  }
  int all = n;
  for (int i = 1; i <= n; i++) {
    if (good[mark[i]]) continue;
    bfs(i, 0);
    bfs(i, 1);
    for (int j = 1; j <= m; j++) {
      if (dp[a[j]][0] != -1 && dp[b[j]][1] != -1) {
        ans[mark[i]] = min(ans[mark[i]], dp[a[j]][0] + dp[b[j]][1] + 1);
      }
    }
  }
  for (int i = 1; i <= cnt; i++) {
    if (good[i]) continue;
    if (co[i] == 1) continue;
    all += (998 * ans[i] + 1);
  }
  cout << all;
}
