#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define llint long long #define inf 1e18 #define rep(x, s, t) for(llint (x) = (s); (x) < (t); (x)++) #define Rep(x, s, t) for(llint (x) = (s); (x) <= (t); (x)++) #define chmin(x, y) (x) = min((x), (y)) #define chmax(x, y) (x) = max((x), (y)) #define mod 998244353 using namespace std; typedef pair P; llint n, m; map mp, mp2; vector G[400005], revG[400005]; vector g[400005]; vector topo; bool used[400005]; int scc[400005]; llint dp[400005]; void tpsort(int v) { used[v] = true; for(int i = 0; i < G[v].size(); i++){ if(!used[G[v][i]]) tpsort(G[v][i]); } topo.push_back(v); } void sccdfs(int v, int id) { used[v] = true; scc[v] = id; for(int i = 0; i < revG[v].size(); i++){ if(!used[revG[v][i]]) sccdfs(revG[v][i], id); } } int main(void) { ios::sync_with_stdio(0); cin.tie(0); cin >> n >> m; llint u, v, id = 0; for(int i = 1; i <= m; i++){ cin >> u >> v; if(mp.count(u) == 0){ mp[u] = ++id; mp2[id] = u; } if(mp.count(v) == 0){ mp[v] = ++id; mp2[id] = v; } G[mp[u]].push_back(mp[v]); revG[mp[v]].push_back(mp[u]); } llint N = id; for(int i = 1; i <= N; i++) if(!used[i]) tpsort(i); reverse(topo.begin(), topo.end()); id = 0; for(int i = 1; i <= N; i++) used[i] = false; for(int i = 0; i < topo.size(); i++) if(!used[topo[i]]) sccdfs(topo[i], ++id); for(int i = 1; i <= N; i++){ chmax(dp[scc[i]], mp2[i]); for(int j = 0; j < G[i].size(); j++){ llint v = G[i][j]; if(scc[v] != scc[i]) g[scc[i]].push_back(scc[v]); } } for(int i = id; i >= 1; i--){ for(int j = 0; j < g[i].size(); j++){ chmax(dp[i], dp[g[i][j]]); } } llint ans = n * (n+1) / 2; for(auto it = mp.begin(); it != mp.end(); it++){ ans += dp[scc[it->second]] - it->first; } cout << ans << endl; return 0; }