[BOJ] 11970. Fence Painting

이정진·2022년 1월 19일
0

PS

목록 보기
38/76
post-thumbnail

Fence Painting

알고리즘 구분 : 수학, 구현

문제

Several seasons of hot summers and cold winters have taken their toll on Farmer John's fence, and he decides it is time to repaint it, along with the help of his favorite cow, Bessie. Unfortunately, while Bessie is actually remarkably proficient at painting, she is not as good at understanding Farmer John's instructions.

If we regard the fence as a one-dimensional number line, Farmer John paints the interval between (x=a) and (x=b). For example, if (a=3) and (b=5), then Farmer John paints an interval of length 2. Bessie, misunderstanding Farmer John's instructions, paints the interval from (x=c) to (x=d), which may possibly overlap with part or all of Farmer John's interval. Please determine the total length of fence that is now covered with paint.

입력
The first line of the input contains the integers (a) and (b), separated by a space ((a < b)).

The second line contains integers (c) and (d), separated by a space ((c < d)).

The values of (a), (b), (c), and (d) all lie in the range (0 \ldots 100), inclusive.

출력
Please output a single line containing the total length of the fence covered with paint.

예제 입력 1
7 10
4 8
예제 출력 1
6

문제 풀이

문제를 해석할 때, 조금 애매한 부분이 있지만, 결론적으로는 Bessie가 칠하게 된 울타리 범위를 구하라는 것이 핵심이다.
John이 지시한 내용을 제대로 이해하지 못하고 C~D구간을 칠했지만, 나중에 A~B구간을 다시 칠하게 되므로 A~B, C~D 구간에서 겹치는 부분을 제외한 총 칠한 울타리 칸 수를 구하면 되는 문제이다.
겹치는 부분을 조건문으로 구분하여 일일이 구현하여 풀었다. 조건을 나누는 것만 해낸다면 바로 풀 수 있는 문제다

소스 코드

#include <bits/stdc++.h>

using namespace std;

vector<int> j;
vector<int> b;
void solve();

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

    for(int i = 0; i < 2; i++) {
        int input;
        cin >> input;
        j.push_back(input);
    }

    for(int i = 0; i < 2; i++) {
        int input;
        cin >> input;
        b.push_back(input);
    }

    solve();

    return 0;
}

void solve() {
    int result;
    
    if(j[0] < b[0]) {
        if(j[1] < b[0]) {
            result = (j[1] - j[0]) + (b[1] - b[0]);
        }
        else if(j[1] >= b[0]) {
            if(j[1] <= b[1]) {
                result = b[1] - j[0];
            }
            else if(j[1] > b[1]) {
                result = j[1] - j[0];
            }
        }
    }
    else if(j[0] > b[0]) {
        if(j[0] > b[1]) {
            result = (j[1] - j[0]) + (b[1] - b[0]);
        }
        else if(j[0] <= b[1]) {
            if(j[1] >= b[1]) {
                result = j[1] - b[0];
            }
            else if(j[1] < b[1]) {
                result = b[1] - b[0];
            }
        }
    }
    else {
        if(j[1] == b[1]) {
            result = j[1] - j[0];
        }
        else if(j[1] > b[1]) {
            result = j[1] - j[0];
        }
        else if(j[1] < b[1]) {
            result = b[1] - b[0];
        }
    }

    cout << result << endl;
}

0개의 댓글