#pragma GCC optimize ("O2") #pragma GCC target ("avx2") #include using namespace std; typedef long long ll; #define rep(i, n) for(int i = 0; i < (n); i++) #define rep1(i, n) for(int i = 1; i <= (n); i++) #define co(x) cout << (x) << "\n" #define cosp(x) cout << (x) << " " #define ce(x) cerr << (x) << "\n" #define cesp(x) cerr << (x) << " " #define pb push_back #define mp make_pair #define chmin(x, y) x = min(x, y) #define chmax(x, y) x = max(x, y) #define Would #define you #define please int N, M; const int NV = 400001; int KL[400001]; vector E[NV], E2[NV]; vector ba, E3[NV]; set vis; map S; int kazu[NV], memo[NV]; int NS; int zaatu(int A) { return lower_bound(KL, KL + M + M, A) - KL; } void dfs1(int a) { int A = zaatu(a); if (vis.find(A) == vis.end()) { vis.insert(A); for (int i : E[A]) dfs1(KL[i]); ba.pb(a); } } void dfs2(int a) { int A = zaatu(a); if (!S[A]) { S[A] = NS; chmax(kazu[NS], a); for (int i : E2[A]) dfs2(KL[i]); } } int dfs3(int A) { if (memo[A]) return memo[A]; int ret = kazu[A]; for (int i : E3[A]) chmax(ret, dfs3(i)); return memo[A] = ret; } int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> N >> M; set list; int kl = 0; int U[200000], V[200000]; rep(i, M) { int u, v; cin >> u >> v; U[i] = u; V[i] = v; KL[kl++] = u; KL[kl++] = v; list.insert(u); list.insert(v); } sort(KL, KL + M + M); rep(i, M) { int u = zaatu(U[i]); int v = zaatu(V[i]); E[u].pb(v); E2[v].pb(u); } for(auto i : list) { dfs1(i); } for (int i = M - 1; i >= 0; i--) if (S[zaatu(ba[i])] == 0) { NS++; dfs2(ba[i]); } for (auto P : list) { int p = zaatu(P); for (int j : E[p]) { if (S[p] != S[j]) E3[S[p]].pb(S[j]); } } //rep1(i, N) { // cesp(i); // int j = zaatu(i); // cesp(j); // ce(S[j]); // for (auto k : E3[S[j]]) { // cesp(k); // }ce(""); //} ll kotae = 0; for (auto i : list) { kotae -= i; int tmp = zaatu(i); int j = S[tmp]; kotae += dfs3(j); } kotae += ll(N) * (N + 1) / 2; co(kotae); Would you please return 0; }