[백준 24310] Painting the Fence (C#, C++) - soo:bak
작성일 :
문제 링크
설명
두 번에 걸쳐 A~B, C~D 구간을 칠했을 때, 중복을 포함한 전체 칠해진 판자의 개수를 구하는 문제입니다. 구간은 양 끝을 포함하며, 역순으로 주어질 수도 있습니다.
접근법
각 구간을 정렬해 [l1, r1], [l2, r2]로 만들고 길이를 구합니다.
겹치는 구간 길이를 계산한 뒤, 두 길이의 합에서 겹치는 길이를 빼면 전체 칠해진 판자 수가 됩니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
class Program {
static void Main() {
var parts = Console.ReadLine()!.Split();
int a = int.Parse(parts[0]);
int b = int.Parse(parts[1]);
int c = int.Parse(parts[2]);
int d = int.Parse(parts[3]);
int l1 = Math.Min(a, b), r1 = Math.Max(a, b);
int l2 = Math.Min(c, d), r2 = Math.Max(c, d);
int len1 = r1 - l1 + 1;
int len2 = r2 - l2 + 1;
int overlap = Math.Max(0, Math.Min(r1, r2) - Math.Max(l1, l2) + 1);
int total = len1 + len2 - overlap;
Console.WriteLine(total);
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int a, b, c, d; cin >> a >> b >> c >> d;
int l1 = min(a, b), r1 = max(a, b);
int l2 = min(c, d), r2 = max(c, d);
int len1 = r1 - l1 + 1;
int len2 = r2 - l2 + 1;
int overlap = max(0, min(r1, r2) - max(l1, l2) + 1);
int total = len1 + len2 - overlap;
cout << total << "\n";
return 0;
}