#include <bits/stdc++.h>
const long long MAXN = 1e5 + 10;
using namespace std;
long long ans = 0, cnt = 0;
bool mark[MAXN];
vector<long long> vec[MAXN], rev[MAXN], ft, node;
queue<long long> q;
void dfs(long long x, vector<long long>* g, vector<long long>& node) {
  mark[x] = 1;
  for (auto u : g[x])
    if (mark[u] == 0) dfs(u, g, node);
  node.push_back(x);
}
bool is_sync() {
  bool isseen[MAXN];
  fill_n(isseen, MAXN, 0);
  for (auto u : node) isseen[u] = 1;
  for (auto u : node)
    for (auto x : vec[u])
      if (isseen[x] == 0) return 0;
  return 1;
}
void bfs() {
  cnt++;
  long long mn = 1e9 + 7;
  bool marki[MAXN];
  long long dis[MAXN];
  fill_n(marki, MAXN, 0);
  for (auto u : node) {
    q.push(u);
    marki[u] = 1;
    while (q.size()) {
      long long x = q.front();
      for (auto i : vec[x]) {
        if (marki[i]) {
          if (i == u) {
            mn = min(mn, dis[x] + 1);
          }
          continue;
        }
        dis[i] = dis[x] + 1;
        marki[i] = 1;
        q.push(i);
      }
      q.pop();
    }
    fill_n(marki, MAXN, 0);
    fill_n(dis, MAXN, 0);
  }
  if (mn == 1e9 + 7) {
    cnt--;
    mn = 0;
  }
  ans += mn;
}
int32_t main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long n, m;
  cin >> n >> m;
  for (long long i = 1; i <= m; i++) {
    long long u, v;
    cin >> u >> v;
    vec[u].push_back(v);
    rev[v].push_back(u);
  }
  for (long long i = 1; i <= n; i++)
    if (mark[i] == 0) dfs(i, vec, ft);
  fill(mark, mark + MAXN, 0);
  for (; ft.size(); ft.pop_back()) {
    long long x = ft.back();
    if (mark[x]) continue;
    dfs(x, rev, node);
    bool b = 0;
    b = is_sync();
    if (b == 1)
      if (b == 1) bfs();
    node.clear();
  }
  cout << 998 * ans + n + cnt;
}
