#include <bits/stdc++.h>
using namespace std;
const int MAX = 5048;
vector<int> adj[MAX];
bool used[MAX];
int dist[MAX][MAX];
void solve(const int test_num) {
  (void)test_num;
  int v, e;
  cin >> v >> e;
  for (int ee = 0, a, b; ee < e; ++ee) {
    cin >> a >> b;
    adj[a].push_back(b);
  }
  memset(dist, 0, sizeof(dist));
  queue<int> que;
  for (int st = 1; st <= v; ++st) {
    que.push(st);
    while (!que.empty()) {
      const int at = que.front();
      que.pop();
      for (const int to : adj[at]) {
        if (dist[st][to] == 0) {
          dist[st][to] = dist[st][at] + 1;
          que.push(to);
        }
      }
    }
  }
  memset(used, false, sizeof(used));
  int res = v;
  for (int at = 1; at <= v; ++at) {
    if (used[at]) continue;
    used[at] = true;
    int min_cycle = dist[at][at];
    bool is_sink = true;
    for (int to = 1; to <= v; ++to) {
      if (dist[at][to] && dist[to][at]) {
        used[to] = true;
        min_cycle = min(min_cycle, dist[to][to]);
      }
      if (dist[at][to] && !dist[to][at]) {
        is_sink = false;
      }
    }
    if (is_sink && min_cycle) {
      res += 998 * min_cycle + 1;
    }
  }
  cout << res << endl;
}
void init() {}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  srand(1223);
  init();
  int tests = 1;
  for (int test = 1; test <= tests; ++test) {
    solve(test);
  }
  return 0;
}
