#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxv = 5555;
int V;
vector<int> G[maxv];
vector<int> rG[maxv];
vector<int> vs;
bool used[maxv];
int cmp[maxv];
void add_edge(int from, int to) {
  G[from].push_back(to);
  rG[to].push_back(from);
}
void dfs(int v) {
  used[v] = true;
  for (int i = 0; i < G[v].size(); ++i) {
    if (!used[G[v][i]]) dfs(G[v][i]);
  }
  vs.push_back(v);
}
void rdfs(int v, int k) {
  used[v] = true;
  cmp[v] = k;
  for (int i = 0; i < rG[v].size(); ++i) {
    if (!used[rG[v][i]]) rdfs(rG[v][i], k);
  }
}
int scc() {
  memset(used, 0, sizeof used);
  vs.clear();
  for (int v = 1; v <= V; ++v) {
    if (!used[v]) dfs(v);
  }
  memset(used, 0, sizeof used);
  int k = 0;
  for (int i = vs.size() - 1; i >= 0; i--) {
    if (!used[vs[i]]) rdfs(vs[i], k++);
  }
  return k;
}
int depth[maxv];
int cycnum, cycsiz;
void findMinCycle(int u, int &mnsiz) {
  int dis[maxv];
  memset(dis, 0x3f, sizeof dis);
  queue<int> q;
  q.push(u);
  dis[u] = 1;
  while (!q.empty()) {
    int v = q.front();
    q.pop();
    for (int i = 0; i < G[v].size(); ++i) {
      int w = G[v][i];
      if (w == u) {
        mnsiz = min(mnsiz, dis[v]);
        return;
      } else {
        if (dis[w] > dis[v] + 1) {
          dis[w] = dis[v] + 1;
          q.push(w);
        }
      }
    }
  }
  mnsiz = 0;
  return;
}
void solve(int x) {
  vector<int> v;
  for (int i = 1; i <= V; ++i) {
    if (cmp[i] == x) {
      v.push_back(i);
      for (int j = 0; j < G[i].size(); ++j) {
        if (cmp[G[i][j]] != x) return;
      }
    }
  }
  int mnsiz = inf;
  for (int i = 0; i < v.size(); i++) {
    findMinCycle(v[i], mnsiz);
  }
  if (mnsiz > 0) {
    cycnum++;
    cycsiz += mnsiz;
  }
  return;
}
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 0; i < m; ++i) {
    int u, v;
    scanf("%d%d", &u, &v);
    add_edge(u, v);
  }
  V = n;
  int mxnum = scc();
  cycnum = 0, cycsiz = 0;
  for (int i = 0; i < mxnum; ++i) {
    solve(i);
  }
  printf("%d\n", V + 998 * cycsiz + cycnum);
  return 0;
}
