#include <bits/stdc++.h>
using namespace std;
const int N = 5050, inF = N;
int n, m, ans, dis[N][N];
bool mark[N];
vector<int> out[N], in[N], topo;
void dfs(int v, vector<int> *nei, vector<int> *vec) {
  mark[v] = true;
  for (int u : nei[v])
    if (mark[u] == false) dfs(u, nei, vec);
  vec->push_back(v);
}
bool sync(vector<int> vec) {
  sort(vec.begin(), vec.end());
  for (int v : vec)
    for (int u : out[v])
      if (binary_search(vec.begin(), vec.end(), u) == false) return false;
  return true;
}
void bfs(int base, int v, queue<int> *q) {
  for (int u : out[v])
    if (dis[base][u] == inF) {
      dis[base][u] = dis[base][v] + 1;
      q->push(u);
    }
}
void BFS(int v) {
  fill(dis[v], dis[v] + n, inF);
  queue<int> q;
  dis[v][v] = 0;
  q.push(v);
  while (q.size()) {
    bfs(v, q.front(), &q);
    q.pop();
  }
}
int min_cycle(vector<int> vec) {
  for (int u : vec) BFS(u);
  int mini = vec.size();
  for (int v : vec)
    for (int u : out[v]) mini = min(mini, 1 + dis[u][v]);
  return mini;
}
int main() {
  ios::sync_with_stdio(false), cin.tie(0);
  cin >> n >> m;
  while (m--) {
    int u, v;
    cin >> u >> v;
    out[--u].push_back(--v);
    in[v].push_back(u);
  }
  for (int v = 0; v < n; v++)
    if (mark[v] == false) dfs(v, out, &topo);
  memset(mark, false, sizeof mark);
  for (; topo.size(); topo.pop_back()) {
    int u = topo.back();
    if (mark[u]) continue;
    vector<int> vec;
    dfs(u, in, &vec);
    if (vec.size() > 1 && sync(vec)) ans += 998 * min_cycle(vec) + 1;
  }
  cout << ans + n;
  return 0;
}
