#41187: 提供一個簡單的思路


sscott0304 (蜜蜂)

學校 : 國立臺東大學
編號 : 145193
來源 : [1.200.152.91]
最後登入時間 :
2024-09-21 20:05:03

#include <bits/stdc++.h>
using namespace std;

int main(){
    ios_base::sync_with_stdio(0); 
    cin.tie(0); 
    cout.tie(0);
    
    int x;
    while (cin >> x) {
        if (cin.fail()) break;

        int from = 0, to = 0, ans = 0;
        map<int, int> m;
        
        for (int i = 0; i < x; i++) {
            cin >> from >> to;
            if (from > to) swap(from, to);
            m[from] = max(m[from], to);
        }
        
        from = -1;
        to = -1;
        
        for (const auto& it : m) {
            if (it.second <= to) {
                continue;
            } else if (it.first > to) {
                ans += to - from;
                from = it.first;
                to = it.second;
            } else if (it.first <= to) {
                to = max(to, it.second);
            }
        }
        
        ans += to - from;
        cout << ans << endl;
    }
    
    return 0;
}