#include <bits/stdc++.h>
using namespace std;
template <class T>
inline void amin(T &x, const T &y) {
  if (y < x) x = y;
}
template <class T>
inline void amax(T &x, const T &y) {
  if (x < y) x = y;
}
template <class Iter>
void rprintf(const char *fmt, Iter begin, Iter end) {
  for (bool sp = 0; begin != end; ++begin) {
    if (sp)
      putchar(' ');
    else
      sp = true;
    printf(fmt, *begin);
  }
  putchar('\n');
}
int N, M;
vector<int> G[5001];
int mat[5001][5001];
int dist[5001][5001];
const int INF = 1 << 29;
bool use[5001];
int len[5001];
void bfs(int s) {
  for (int i = 0, i_len = (N); i < i_len; ++i) len[i] = INF;
  queue<int> Q, L;
  Q.push(s);
  L.push(0);
  while (!Q.empty()) {
    int v = Q.front();
    Q.pop();
    int l = L.front();
    L.pop();
    for (__typeof((G[v]).begin()) e = (G[v]).begin(), e_end = (G[v]).end();
         e != e_end; ++e) {
      if (len[*e] > l + 1) {
        len[*e] = l + 1;
        Q.push(*e);
        L.push(len[*e]);
      }
    }
  }
}
int main() {
  scanf("%d%d", &N, &M);
  for (int i = 0, i_len = (N); i < i_len; ++i)
    for (int j = 0, j_len = (N); j < j_len; ++j) mat[i][j] = INF;
  for (int i = 0, i_len = (M); i < i_len; ++i) {
    int x, y;
    scanf("%d%d", &x, &y);
    x--;
    y--;
    G[x].push_back(y);
    mat[x][y] = 1;
  }
  for (int i = 0, i_len = (N); i < i_len; ++i) {
    bfs(i);
    for (int j = 0, j_len = (N); j < j_len; ++j) dist[i][j] = len[j];
  }
  int ans = N;
  for (int s = 0, s_len = (N); s < s_len; ++s)
    if (!use[s]) {
      int cycle = INF;
      for (int i = 0, i_len = (N); i < i_len; ++i) {
        if (dist[s][i] < INF && dist[i][s] == INF) {
          cycle = INF;
          break;
        }
        if (i == s || (dist[i][s] != INF && dist[s][i] != INF)) {
          use[i] = true;
          amin(cycle, dist[i][i]);
        }
      }
      if (cycle < INF) {
        ans += 998 * cycle + 1;
      }
    }
  printf("%d\n", ans);
  return 0;
}
