#include using namespace std; struct strongly_connected_components{ vector> scc; vector c; void dfs1(vector> &E, vector &used, vector &t, int v){ for (int w : E[v]){ if (!used[w]){ used[w] = true; dfs1(E, used, t, w); } } t.push_back(v); } void dfs2(vector> &E, vector &used, int v){ scc.back().push_back(v); for (int w : E[v]){ if (!used[w]){ used[w] = true; dfs2(E, used, w); } } } strongly_connected_components(vector> G){ int V = G.size(); vector> E1(V), E2(V); for (int i = 0; i < V; i++){ for (int j : G[i]){ E1[i].push_back(j); E2[j].push_back(i); } } vector used(V, false); vector t; for (int i = 0; i < V; i++){ if (!used[i]){ used[i] = true; dfs1(E1, used, t, i); } } reverse(t.begin(), t.end()); vector used2(V, false); for (int i = 0; i < V; i++){ if (!used2[t[i]]){ used2[t[i]] = true; scc.push_back(vector()); dfs2(E2, used2, t[i]); } } c = vector(V); int sz = scc.size(); for (int i = 0; i < sz; i++){ for (int j : scc[i]){ c[j] = i; } } } int size(){ return scc.size(); } int operator [](int k){ return c[k]; } }; int main(){ int N, M; cin >> N >> M; vector B(M), C(M); for (int i = 0; i < M; i++){ cin >> B[i] >> C[i]; } vector xval; for (int i = 0; i < M; i++){ xval.push_back(B[i]); xval.push_back(C[i]); } sort(xval.begin(), xval.end()); xval.erase(unique(xval.begin(), xval.end()), xval.end()); int cnt = xval.size(); long long ans = (long long) N * (N + 1) / 2; for (int x : xval){ ans -= x; } map mp; for (int i = 0; i < cnt; i++){ mp[xval[i]] = i; } for (int i = 0; i < M; i++){ B[i] = mp[B[i]]; C[i] = mp[C[i]]; } vector> E(cnt); for (int i = 0; i < M; i++){ E[B[i]].push_back(C[i]); } strongly_connected_components S(E); int cnt2 = S.size(); vector mx(cnt2); for (int i = 0; i < cnt; i++){ mx[S[i]] = max(mx[S[i]], xval[i]); } vector> f(cnt2); for (int i = 0; i < M; i++){ int x = S[B[i]]; int y = S[C[i]]; if (x != y){ f[x].push_back(y); } } for (int i = cnt2 - 1; i >= 0; i--){ for (int j : f[i]){ mx[i] = max(mx[i], mx[j]); } } for (int i = 0; i < cnt; i++){ ans += mx[S[i]]; } cout << ans << endl; }