#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline bool chkmin(T &a, const T &b) {
  return a > b ? a = b, 1 : 0;
}
template <typename T>
inline bool chkmax(T &a, const T &b) {
  return a < b ? a = b, 1 : 0;
}
const int oo = 0x3f3f3f3f;
const int maxn = 5050, maxm = 5050;
int n, m;
vector<int> adj[maxn + 5];
inline void get_dis(int S, int *dis) {
  static int q[maxn + 5];
  static bool vis[maxn + 5];
  memset(vis, 0, sizeof vis);
  for (int i = (0), i_end_ = (n); i < i_end_; ++i) dis[i] = oo;
  int head = 0, rear = 0;
  dis[S] = 0;
  vis[S] = 1;
  q[rear++] = S;
  while (head != rear) {
    int first = q[head++];
    for (auto second : adj[first]) {
      if (vis[second]) continue;
      vis[second] = 1;
      q[rear++] = second;
      dis[second] = dis[first] + 1;
    }
  }
}
int dis[maxn + 5][maxn + 5];
bool in[maxn + 5];
int main() {
  scanf("%d%d", &n, &m);
  for (int i = (0), i_end_ = (m); i < i_end_; ++i) {
    int u, v;
    scanf("%d%d", &u, &v), --u, --v;
    adj[u].push_back(v);
  }
  for (int i = (0), i_end_ = (n); i < i_end_; ++i) get_dis(i, dis[i]);
  int ans = n;
  for (int i = (0), i_end_ = (n); i < i_end_; ++i)
    if (!in[i]) {
      vector<int> all;
      bool find = 0;
      int Min = oo;
      for (int j = (0), j_end_ = (n); j < j_end_; ++j)
        if (dis[i][j] < oo && dis[j][i] < oo) {
          all.push_back(j);
          assert(!in[j]);
          if (!find) {
            for (auto k : adj[j])
              if (dis[i][k] >= oo || dis[k][i] >= oo) {
                find = 1;
                break;
              } else
                chkmin(Min, 1 + dis[k][j]);
          }
          in[j] = 1;
        }
      if (!find && (int((all).size())) > 1) ans += 998 * Min + 1;
    }
  printf("%d\n", ans);
  return 0;
}
