#include <bits/stdc++.h>
using namespace std;
const int N = 5e3 + 1;
int n, m, vis[N], cnt, d[N], mark[N];
vector<int> go[N], to[N], scc[N], ord;
void read_input() {
  cin >> n >> m;
  for (int i = 0, u, v; i < m; i++) {
    cin >> u >> v;
    --u, --v;
    go[u].push_back(v);
    to[v].push_back(u);
  }
}
void dfs_ts(int u) {
  vis[u] = 1;
  for (int v : go[u])
    if (vis[v] == 0) dfs_ts(v);
  ord.push_back(u);
}
void dfs(int u) {
  scc[cnt].push_back(u);
  mark[u] = cnt + 1;
  for (int v : to[u])
    if (mark[v] == 0) dfs(v);
}
void kosaraju() {
  for (int u = 0; u < n; u++)
    if (vis[u] == 0) dfs_ts(u);
  for (int i = n - 1; i >= 0; i--)
    if (mark[ord[i]] == 0) {
      dfs(ord[i]);
      cnt++;
    }
}
bool out_edge(vector<int> vec) {
  for (int u : vec)
    for (int v : go[u])
      if (mark[v] != mark[u]) return true;
  return false;
}
int bfs(int str) {
  queue<int> q;
  q.push(str);
  d[str] = 0;
  while (q.size()) {
    int u = q.front();
    q.pop();
    for (int v : go[u]) {
      if (v == str) return d[u] + 1;
      if (d[u] + 1 < d[v]) {
        d[v] = d[u] + 1;
        q.push(v);
      }
    }
  }
}
int min_cycle(vector<int> vec) {
  int res = 1e9;
  for (int u : vec) {
    memset(d, 31, sizeof d);
    res = min(bfs(u), res);
  }
  return res;
}
void write_output() {
  long long ans = 0;
  for (int i = 0; i < cnt; i++)
    if (scc[i].size() == 1 || out_edge(scc[i]) == true)
      ans += scc[i].size();
    else
      ans += min_cycle(scc[i]) * 998 + 1 + scc[i].size();
  cout << ans << endl;
}
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0);
  read_input(), kosaraju(), write_output();
}
