#include <bits/stdc++.h>
using namespace std;
const int maxx = 5005;
vector<int> ad[maxx], rad[maxx], scc[maxx];
stack<int> st;
bool vis[maxx];
queue<int> q;
int n, m, comp[maxx], d[maxx];
void dfs(int root, vector<int> adj[maxx], int c) {
  vis[root] = true;
  for (int x : adj[root])
    if (!vis[x]) dfs(x, adj, c);
  if (c == -1)
    st.push(root);
  else
    scc[c].push_back(root), comp[root] = c;
}
int bfs(int root) {
  int r = maxx;
  vis[root] = true;
  q.push(root);
  d[root] = 0;
  while (q.size()) {
    int x = q.front();
    q.pop();
    for (int y : ad[x]) {
      if (!vis[y])
        vis[y] = true, d[y] = d[x] + 1, q.push(y);
      else if (y == root)
        r = min(r, d[x] + 1);
    }
  }
  return r;
}
int get_ans(int c) {
  int e = maxx;
  for (int x : scc[c]) {
    while (!q.empty()) q.pop();
    for (int u : scc[c]) vis[u] = false;
    e = min(e, bfs(x));
  }
  return (e == maxx ? 0 : e);
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int u, v;
    cin >> u >> v;
    u--, v--;
    ad[u].push_back(v);
    rad[v].push_back(u);
  }
  for (int i = 0; i < n; i++)
    if (!vis[i]) dfs(i, ad, -1);
  fill(vis, vis + maxx, false);
  int c = 0;
  while (st.size()) {
    int x = st.top();
    st.pop();
    if (!vis[x]) dfs(x, rad, c++);
  }
  int sum = 0, t = 0;
  for (int i = 0; i < c; i++) {
    bool b = true;
    for (int x : scc[i]) {
      for (int y : ad[x])
        if (comp[x] != comp[y]) b = false;
    }
    if (!b) continue;
    int g = get_ans(i);
    sum += g, t += (g != 0);
  }
  cout << sum * 998 + t + n << endl;
  return 0;
}
