본문 바로가기
알고리즘/백준

백준 1911 흙길 보수하기 C++

by ash9river 2025. 1. 15.

간단한 해설

 

진짜 간단하다.

 

이전에 판자를 어디까지 놓았는지 기억하면 된다.

 

그런데, 사소한 계산에서 실수를 하기 쉬워서 조금 성가셨다.

 

 

    if(lastPanel>=v[i].second) continue;
    if(lastPanel>=v[i].first) v[i].first=lastPanel+1;
    if(v[i].second-v[i].first<=0) continue;

    if((v[i].second-v[i].first)%l!=0){
        lastPanel=v[i].second-1+l-(v[i].second-v[i].first)%l;
        ans+=(v[i].second-v[i].first)/l+1;
    }
    else{
        lastPanel=v[i].second-1;
        ans+=(v[i].second-v[i].first)/l;
    }

 

스위핑으로 인한 조건 분기를 생각하자...

 

 

 

 

#include <iostream>
#include <vector>
#include <algorithm>
#define ll long long
using namespace std;
int main(){
    cin.tie(0);
    ios_base::sync_with_stdio(0);
    ll n,l;
    cin>>n>>l;
    vector<pair<ll,ll>> v(n);
    for(ll i=0;i<n;++i){
        cin>>v[i].first>>v[i].second;
    }
    sort(v.begin(),v.end());
    ll ans=0;
    ll lastPanel=-1;
    for(ll i=0;i<n;++i){
        if(lastPanel>=v[i].second) continue;
        if(lastPanel>=v[i].first) v[i].first=lastPanel+1;
        if(v[i].second-v[i].first<=0) continue;

        if((v[i].second-v[i].first)%l!=0){
            lastPanel=v[i].second-1+l-(v[i].second-v[i].first)%l;
            ans+=(v[i].second-v[i].first)/l+1;
        }
        else{
            lastPanel=v[i].second-1;
            ans+=(v[i].second-v[i].first)/l;
        }
    }
    cout<<ans;
}

'알고리즘 > 백준' 카테고리의 다른 글

백준 10282 해킹 C++  (0) 2025.02.11
백준 28449 누가 이길까 C++  (0) 2025.02.08
백준 2636 치즈 C++  (0) 2025.01.09
백준 2141 우체국 C++  (0) 2025.01.09
백준 1456 거의 소수 C++  (0) 2025.01.08