BOJ 2170 선 긋기

1 개요[ | ]

BOJ 2170 선 긋기

2 C++[ | ]

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

int N;
vector<pair<int, int>> lines;

void solve() {
    // 선의 시작점을 기준으로 정렬
    sort(lines.begin(), lines.end());

    // 선의 길이 계산
    int total_length = 0;
    int start = -1e9, end = -1e9; // 아주 작은 값으로 초기화

    for (auto &line : lines) {
        // 현재 선이 이전 선과 겹치지 않는 경우
        if (line.first > end) {
            total_length += end - start;
            start = line.first;
            end = line.second;
        }
        // 겹치는 경우
        else if (line.second > end) {
            end = line.second;
        }
    }
    // 마지막 선 추가
    total_length += end - start;
    cout << total_length;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> N;
    lines.resize(N);
    for (int i = 0; i < N; ++i) {
        cin >> lines[i].first >> lines[i].second;
    }
    solve();
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}