#include <bits/stdc++.h>

using namespace std;

#define int long long
#define pi pair<int,int>
#define pb(x) push_back(x)
#define ff first
#define ss second
#define all(x) x.begin(), x.end()
#define dbg(x) cout << #x << ": " << x << "\n"
#define dbg2(x, y) cout <<"{ " << #x  <<", "<< #y<< " }"<< ": " <<"{ " << x  <<", "<< y<< " }" << "\n" 
const int MAX_N = 1e5 + 1;
const int MOD = 1e9 + 7;
const int INF = 1e18;

void dfs(int st, int i, vector<int> adj[], vector<bool>& vis, vector<vector<int>>& poss){
	if(vis[i]) return;
	vis[i] = true;
	poss[st][i] = true;
	for(int j: adj[i]){
		dfs(st, j, adj, vis, poss);
	}
}

void solve() {
	int n, m; cin >> n >> m;
	vector<int> adj[n];
	vector<vector<int>> poss(n, vector<int>(n, 0));
	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++){
		vector<bool> vis(n, false); 
		dfs(i, i, adj, vis, poss);
	}
	int ans = 0;
	for(auto x: poss){
		for(auto y: x){
			ans += y;
		}
	}
	cout << ans << "\n";
}

int32_t main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int tc = 1;
    // cin >> tc;
    for (int t = 1; t <= tc; t++) {
        solve();
    }
}
#include <bits/stdc++.h>

#define INF 1e9
#define LINF (1LL << 63 - 1)
#define rep(i,n)for(int i=0;(i)<(int)(n);i++)
#define REP(i,a,b)for(int i=(int)(a);(i)<=(int)(b);i++)
#define ALL(a)  (a).begin(),(a).end()
// #define chmax(a, b) a = max(a, b)
// #define chmin(a, b) a = min(a, b)
#define pb push_back
#define fi first
#define se second
#define sz(x) ((int)x.size())

using namespace std;
//using namespace atcoder;
using ld = long double;
using ll = long long;
using P = pair<ll, ll>;

template<typename T> bool chmin(T& a, const T& b) { if(a > b){ a = b; return 1;} return 0; }
template<typename T> bool chmax(T& a, const T& b) { if(a < b){ a = b; return 1;} return 0; }

const ll ZER = 0;
const ll MOD = 1e9 + 7;




int main(){
    // std::cin.tie(0);
    // std::ios::sync_with_stdio(false);

    int h, w;
    cin >> h >> w;
    ll sum = 0, mi = INF * INF;
    vector<vector<ll>> s(h, vector<ll> (w));
    rep(i, h)rep(j, w)cin >> s[i][j];
    rep(i, h){
        rep(j, w){
            chmin(mi, s[i][j]);
        }
    }
    rep(i, h){
        rep(j, w){
            sum += s[i][j] - mi;
        }
    }
    cout << sum << endl;
}