#include <bits/stdc++.h>
using namespace std;
const int maxn = 5010;
int m, n, tmp, Ans, dp[maxn][maxn], visit[maxn], col[maxn];
vector<int> moa[maxn], in[maxn], out[maxn], tp;
queue<int> q;
void dfs_1(int i) {
  visit[i] = 1;
  for (auto A : out[i])
    if (!visit[A]) dfs_1(A);
  tp.push_back(i);
}
void dfs_2(int i) {
  col[i] = tmp;
  moa[tmp].push_back(i);
  for (auto A : in[i])
    if (!col[A]) dfs_2(A);
}
void topo() {
  tmp = 1;
  for (int y = 1; y <= n; y++)
    if (!visit[y]) dfs_1(y);
  reverse(tp.begin(), tp.end());
  for (auto A : tp)
    if (!col[A]) dfs_2(A), tmp++;
}
void bfs(int i) {
  dp[i][i] = 0;
  q.push(i);
  while (q.size()) {
    int x = q.front();
    q.pop();
    for (auto A : out[x])
      if (dp[i][A] > n) dp[i][A] = dp[i][x] + 1, q.push(A);
  }
  dp[i][i] = 1e5;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie();
  cin >> n >> m;
  Ans = n;
  while (m--) {
    int i, j;
    cin >> i >> j;
    in[j].push_back(i);
    out[i].push_back(j);
  }
  topo();
  for (int mo = 1; mo < tmp; mo++) {
    bool e = 0;
    for (auto A : moa[mo])
      for (auto B : out[A])
        if (col[B] != col[A]) e = 1;
    if (e || moa[mo].size() == 1) continue;
    for (auto A : moa[mo])
      for (auto B : moa[mo]) dp[A][B] = 1e5;
    for (auto A : moa[mo]) bfs(A);
    int ret = 1e5;
    for (auto A : moa[mo])
      for (auto B : moa[mo]) ret = min(ret, dp[A][B] + dp[B][A]);
    Ans += 998 * ret + 1;
  }
  cout << Ans;
}
