#include #ifndef DUMP #define DUMP(...) (void)0 #endif using namespace std; struct graph { struct edge { int src, dst; int operator-(int v) const { return src ^ dst ^ v; } }; int n, m; vector edges; vector>> adj; graph(int _n = 0) : n(_n), m(0), adj(n) {} int add(const edge& e, bool directed = false) { edges.push_back(e); adj[e.src].emplace_back(m, e.dst); if (not directed) adj[e.dst].emplace_back(m, e.src); return m++; } }; int main() { cin.tie(nullptr)->sync_with_stdio(false); int n, m; cin >> n >> m; vector b(m), c(m); for (int i = 0; i < m; ++i) { cin >> b[i] >> c[i]; } auto x = b; x.insert(end(x), begin(c), end(c)); sort(begin(x), end(x)); x.erase(unique(begin(x), end(x)), end(x)); graph g(size(x)); for (int i = 0; i < m; ++i) { b[i] = lower_bound(begin(x), end(x), b[i]) - begin(x); c[i] = lower_bound(begin(x), end(x), c[i]) - begin(x); g.add({c[i], b[i]}, true); } auto res = (int64_t)n * (n + 1) / 2; vector vis(n); for (int s = g.n; s--;) { if (vis[s]) continue; auto dfs = [&](auto&& self, int v) -> void { res += x[s] - x[v]; vis[v] = true; for (auto [id, u] : g.adj[v]) { if (vis[u]) continue; self(self, u); } }; dfs(dfs, s); } cout << res << '\n'; }