#include <bits/stdc++.h>
using namespace std;
int const N = 5000 + 20, INF = 1e8;
int n, m, dist[N][N], last[N], min_cyc[N];
vector<int> adj[N];
inline bool smin(int &a, int b) { return a > b ? a = b, 1 : 0; }
void bfs(int start) {
  int q[N], h = 0, t = 0;
  for (int i = 0; i < n; i++) dist[start][i] = INF;
  dist[start][start] = 0;
  q[t++] = start;
  while (h < t) {
    int v = q[h++];
    for (auto u : adj[v])
      if (dist[start][u] > dist[start][v] + 1) {
        dist[start][u] = dist[start][v] + 1;
        q[t++] = u;
      }
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  for (int i = 0; i < m; i++) {
    int u, v;
    cin >> u >> v;
    u--, v--;
    adj[u].push_back(v);
  }
  for (int i = 0; i < n; i++) bfs(i);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      if (dist[i][j] + dist[j][i] < INF) last[i] = j;
  for (int i = 0; i < n; i++) min_cyc[last[i]] = INF;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      if (dist[i][j] < INF && i != j) {
        if (last[i] != last[j])
          min_cyc[last[i]] = -1;
        else
          smin(min_cyc[last[i]], dist[i][j] + dist[j][i]);
      }
  int ans = n;
  for (int i = 0; i < n; i++)
    if (last[i] == i && ~min_cyc[i] && min_cyc[i] != INF) {
      ans += 998 * min_cyc[i] + 1;
    }
  cout << ans << '\n';
}
