#include <bits/stdc++.h>
using namespace std;
const int MAXN = 5010;
int n, m, gdje[MAXN], a[MAXN], b[MAXN], cyc, out[MAXN], len;
vector<int> v[MAXN], comp[MAXN], v1[MAXN];
stack<int> s;
int dis[MAXN], low[MAXN], bio[MAXN];
int tajm, komp;
void dfs(int cvor) {
  tajm++;
  dis[cvor] = low[cvor] = tajm;
  bio[cvor] = 1;
  s.push(cvor);
  for (int i = (0); i < int((int)v[cvor].size()); i++) {
    int ncvor = v[cvor][i];
    if (bio[ncvor] == 2) continue;
    if (bio[ncvor] == 1) {
      low[cvor] = min(low[cvor], dis[ncvor]);
      continue;
    }
    dfs(ncvor);
    low[cvor] = min(low[cvor], low[ncvor]);
  }
  if (dis[cvor] == low[cvor]) {
    int t;
    do {
      t = s.top();
      s.pop();
      gdje[t] = komp;
      comp[komp].push_back(t);
      bio[t] = 2;
    } while (t != cvor);
    komp++;
  }
}
int bfs(int x, int t) {
  memset(bio, 0, sizeof bio);
  queue<int> q;
  q.push(x);
  q.push(0);
  while (!q.empty()) {
    int cvor = q.front();
    q.pop();
    int d = q.front();
    q.pop();
    if (cvor == x && d) return d;
    for (int i = (0); i < int((int)v[cvor].size()); i++) {
      int ncvor = v[cvor][i];
      if (gdje[ncvor] != t || bio[ncvor]) continue;
      bio[ncvor] = 1;
      q.push(ncvor);
      q.push(d + 1);
    }
  }
  return 0;
}
int solve(int K) {
  int ret = MAXN;
  for (int i = (0); i < int((int)comp[K].size()); i++)
    ret = min(ret, bfs(comp[K][i], K));
  return ret;
}
int main() {
  scanf("%d %d", &n, &m);
  for (int i = (0); i < int(m); i++) {
    scanf("%d %d", &a[i], &b[i]);
    v[a[i]].push_back(b[i]);
  }
  for (int i = (1); i < int(n + 1); i++)
    if (!bio[i]) dfs(i);
  for (int i = (0); i < int(m); i++) {
    int x = gdje[a[i]];
    int y = gdje[b[i]];
    if (x != y) {
      v1[x].push_back(y);
      out[x]++;
    }
  }
  for (int i = (0); i < int(komp); i++) {
    if (!out[i]) {
      int tmp = solve(i);
      len += tmp;
      cyc += (tmp > 0);
    }
  }
  printf("%d\n", 998 * len + n + cyc);
  return 0;
}
