BOJ 2170 선 긋기
BOJ 2170 선 긋기
https://www.acmicpc.net/problem/2170
문제
매우 큰 도화지에 자를 대고 선을 그으려고 한다. 선을 그을 때에는 자의 한 점에서 다른 한 점까지 긋게 된다. 선을 그을 때에는 이미 선이 있는 위치에 겹쳐서 그릴 수도 있는데, 여러 번 그은 곳과 한 번 그은 곳의 차이를 구별할 수 없다고 하자.
이와 같은 식으로 선을 그었을 때, 그려진 선(들)의 총 길이를 구하는 프로그램을 작성하시오. 선이 여러 번 그려진 곳은 한 번씩만 계산한다.
입력
첫째 줄에 선을 그은 횟수 N (1 ≤ N ≤ 1,000,000)이 주어진다. 다음 N개의 줄에는 선을 그을 때 선택한 두 점의 위치 x, y (-1,000,000,000 ≤ x < y ≤ 1,000,000,000)가 주어진다.
출력
첫째 줄에 그은 선의 총 길이를 출력한다.
예제 입력 1
4 1 3 2 5 3 5 6 7
예제 출력 1
5
코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
static PriorityQueue<Point> queue = new PriorityQueue<>(Comparator.comparingInt(point -> point.x));
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
for (int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
queue.offer(new Point(x, y));
}
int answer = calculateTotalLength();
System.out.println(answer);
}
static int calculateTotalLength() {
int totalLength = 0;
Point maxLengthLine = queue.poll();
while (!queue.isEmpty()) {
Point check = queue.poll();
if(maxLengthLine.y >= check.x) {
if(maxLengthLine.y < check.y) {
maxLengthLine.y = check.y;
}
} else {
totalLength += maxLengthLine.y - maxLengthLine.x;
maxLengthLine = check;
}
}
totalLength += maxLengthLine.y - maxLengthLine.x;
return totalLength;
}
}
This post is licensed under CC BY 4.0 by the author.