#include #include #include #include #include #include #include #include #include using namespace std; #pragma warning (disable: 4996) long long N, M; long long B[1 << 19], C[1 << 19]; long long col[1 << 19]; vector X; vector G[1 << 19]; int main() { // Step #1. 入力 cin >> N >> M; for (int i = 1; i <= M; i++) { cin >> B[i] >> C[i]; X.push_back(B[i]); X.push_back(C[i]); } // Step #2. 座標圧縮 sort(X.begin(), X.end()); X.erase(unique(X.begin(), X.end()), X.end()); for (int i = 1; i <= M; i++) B[i] = lower_bound(X.begin(), X.end(), B[i]) - X.begin(); for (int i = 1; i <= M; i++) C[i] = lower_bound(X.begin(), X.end(), C[i]) - X.begin(); for (int i = 1; i <= M; i++) G[C[i]].push_back(B[i]); // Step #3. 計算 for (int i = 0; i < X.size(); i++) col[i] = -1; for (int i = X.size() - 1; i >= 0; i--) { if (col[i] != -1) continue; queue Q; Q.push(i); col[i] = i; while (!Q.empty()) { int pos = Q.front(); Q.pop(); for (int j : G[pos]) { if (col[j] == -1) { col[j] = i; Q.push(j); } } } } // Step #4. 答えを求める long long Answer = N * (N + 1LL) / 2LL; for (int i = 0; i < X.size(); i++) { Answer += (X[col[i]] - X[i]); } cout << Answer << endl; return 0; }