#include <bits/stdc++.h>
using namespace std;
template <class T>
inline bool getmin(T *a, const T &b) {
  if (b < *a) {
    *a = b;
    return true;
  }
  return false;
}
template <class T>
inline bool getmax(T *a, const T &b) {
  if (b > *a) {
    *a = b;
    return true;
  }
  return false;
}
template <class T>
inline void read(T *a) {
  char c;
  while (isspace(c = getchar())) {
  }
  bool flag = 0;
  if (c == '-')
    flag = 1, *a = 0;
  else
    *a = c - 48;
  while (isdigit(c = getchar())) *a = *a * 10 + c - 48;
  if (flag) *a = -*a;
}
const int mo = 1000000007;
template <class T>
T pow(T a, T b, int c = mo) {
  T res = 1;
  for (T i = 1; i <= b; i <<= 1, a = 1LL * a * a % c)
    if (b & i) res = 1LL * res * a % c;
  return res;
}
const int N = 10100;
int d[N];
int low[N], dfn[N], idx;
bool instack[N];
stack<int> S;
struct node {
  int p, nextt;
} edge[N];
int color[N], tot;
int head[N], cnt;
int n, m;
void ae(int a, int b) {
  edge[++cnt].p = b;
  edge[cnt].nextt = head[a];
  head[a] = cnt;
}
int bfs(int s) {
  static queue<int> q;
  while (!q.empty()) q.pop();
  for (int i = (1); i <= (n); ++i) d[i] = 0;
  d[s] = 1;
  q.push(s);
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    if (u == s && d[u] > 1) return d[u] - 1;
    for (int k = head[(u)]; k; k = edge[k].nextt) {
      int v = edge[k].p;
      if (color[u] == color[v] && d[v] <= 1) {
        d[v] = d[u] + 1;
        q.push(v);
      }
    }
  }
  return 0;
}
int calc(int x) {
  int ans = n;
  for (int i = (1); i <= (n); ++i)
    if (color[i] == x) getmin(&ans, bfs(i));
  return ans;
}
int size[N];
void tarjan(int u) {
  low[u] = dfn[u] = ++idx;
  S.push(u);
  instack[u] = 1;
  for (int k = head[(u)]; k; k = edge[k].nextt) {
    int v = edge[k].p;
    if (!dfn[v]) {
      tarjan(v);
      getmin(low + u, low[v]);
    } else if (instack[v])
      getmin(low + u, dfn[v]);
  }
  if (low[u] == dfn[u]) {
    ++tot;
    size[tot] = 1;
    instack[u] = 0;
    color[u] = tot;
    while (S.top() != u) {
      int v = S.top();
      size[tot]++;
      instack[v] = 0;
      color[v] = tot;
      S.pop();
    }
    S.pop();
  }
}
bool vis[N];
int main() {
  cin >> n >> m;
  for (int i = (1); i <= (m); ++i) {
    int x, y;
    read(&x);
    read(&y);
    ae(x, y);
  }
  for (int i = (1); i <= (n); ++i)
    if (!dfn[i]) tarjan(i);
  for (int i = (1); i <= (n); ++i)
    for (int k = head[(i)]; k; k = edge[k].nextt) {
      int j = edge[k].p;
      if (color[i] != color[j]) vis[color[i]] = 1;
    }
  int ans = 0, r = n;
  for (int i = (1); i <= (tot); ++i)
    if (!vis[i]) {
      int t = calc(i);
      if (!t) continue;
      r -= t;
      ans += 1000 + (t - 1) * 999;
    }
  cout << ans + r << endl;
  return 0;
}
