#include <bits/stdc++.h>
using namespace std;
const int N = 5 * 1000 + 20;
int n, m, vis[N], mark[N], ans;
vector<int> adj[N], Adj[N], topol, mf[N], snc;
void dfs(int v) {
  vis[v] = 1;
  for (auto u : adj[v])
    if (!vis[u]) dfs(u);
  topol.push_back(v);
}
void DFS(int v, int c) {
  vis[v] = c;
  for (auto u : Adj[v])
    if (!vis[u]) DFS(u, c);
}
int get(int x) {
  if (mf[x].size() == 1) return 0;
  int mx = 10000;
  for (auto w : mf[x]) {
    for (auto i : mf[x]) mark[i] = INT_MAX;
    mark[w] = 1;
    queue<int> Q;
    Q.push(w);
    while (!Q.empty()) {
      int v = Q.front();
      Q.pop();
      for (auto u : adj[v]) {
        if (u == w) mx = min(mx, mark[v]);
        if (mark[u] > mark[v] + 1) mark[u] = mark[v] + 1, Q.push(u);
      }
    }
  }
  return mx;
}
int main() {
  ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  cin >> n >> m;
  for (int i = 0, u, v; i < m; i++) {
    cin >> v >> u;
    adj[v].push_back(u);
    Adj[u].push_back(v);
  }
  for (int i = 1; i <= n; i++)
    if (!vis[i]) dfs(i);
  memset(vis, 0, sizeof vis);
  reverse(topol.begin(), topol.end());
  int cnt = 0;
  for (auto u : topol)
    if (!vis[u]) DFS(u, ++cnt);
  for (int i = 1; i <= n; i++) mf[vis[i]].push_back(i);
  for (int i = 1; i <= cnt; i++) {
    int tmp = 0;
    for (auto v : mf[i])
      for (auto u : adj[v])
        if (vis[u] != i) tmp++;
    if (tmp)
      ans += (int)mf[i].size();
    else {
      ans += get(i) * 999 + 1;
      ans += (int)mf[i].size() - get(i);
      if (get(i) == 0) ans--;
    }
  }
  cout << ans << endl;
  return 0;
}
