코딩테스트/백준

[골5] 2170 - 선 긋기

ShovelingLife 2022. 11. 23. 13:00
#include <limits.h>
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

#define y first
#define x second

bool cmp(pair<int,int>& lRef, pair<int,int>& rRef)
{
    return lRef.y < rRef.y;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);

    int n; cin >> n;
    vector<pair<int, int>> v(n);

    for (int i = 0; i < n; i++)
        cin >> v[i].y >> v[i].x;

    sort(v.begin(), v.end(), cmp);
    int s = INT_MIN, e = INT_MIN, ans = 0;

    for (int i = 0; i < n; i++)
    {
    	if (e < v[i].y) // 새 선분
        {
            ans += e - s;
            s = v[i].y;
        }
        if (e < v[i].x) // 선분 확장
            e = v[i].x;
    }
    // 마지막 선분 처리
    ans += e - s;
    cout << ans;
}