알고리즘/그리디

[백준/그리디/C++] 2170번 선 긋기

데메즈 2023. 4. 11. 18:47
728x90
반응형

문제는 여기!

#include <bits/stdc++.h>

using namespace std;
int N;
vector<pair<int, int>> arr;
int answer = 0;

void solve(){
    int start = arr[0].first, end = arr[0].second;

    for(int i=1; i<N; i++){
        if(arr[i].first > end){
            answer = answer + end - start;
            start = arr[i].first;
            end = arr[i].second;
        } else if(arr[i].second > end){
            end = arr[i].second;
        }
    }
    answer = answer + end - start;
}

void input(){
    cin >> N;
    for(int i=0; i<N; i++){
        int x, y;
        cin >> x >> y;
        arr.push_back({x, y});
    }
    sort(arr.begin(), arr.end());
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    input();
    solve();
    cout << answer;

    return 0;
}
728x90
반응형