|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.IOException; |
| 3 | +import java.io.InputStreamReader; |
| 4 | +import java.util.PriorityQueue; |
| 5 | +import java.util.StringTokenizer; |
| 6 | + |
| 7 | +public class SB_2170 { |
| 8 | + public static void main(String[] args) throws IOException { |
| 9 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 10 | + StringTokenizer st; |
| 11 | + |
| 12 | + PriorityQueue<Node> pq = new PriorityQueue<>(); |
| 13 | + |
| 14 | + int N = Integer.parseInt(br.readLine()); |
| 15 | + for (int i = 0; i < N; i++) { |
| 16 | + st = new StringTokenizer(br.readLine()); |
| 17 | + int s = Integer.parseInt(st.nextToken()); |
| 18 | + int e = Integer.parseInt(st.nextToken()); |
| 19 | + pq.offer(new Node(s, e)); |
| 20 | + } |
| 21 | + |
| 22 | + Node first = pq.poll(); |
| 23 | + int start = first.s; |
| 24 | + int end = first.e; |
| 25 | + int cnt = 0; |
| 26 | + |
| 27 | + while (!pq.isEmpty()) { |
| 28 | + Node cur = pq.poll(); |
| 29 | + if (start <= cur.s && cur.s <= end) { // 현재 선분이랑 겹칠 경우 |
| 30 | + end = Math.max(end, cur.e); // 더 큰 끝값으로 업데이트 |
| 31 | + continue; |
| 32 | + } |
| 33 | + |
| 34 | + // 겹치지 않음 (== 새로운 선분 시작) |
| 35 | + cnt += end - start; // 지금까지의 선분 길이 더해주기 |
| 36 | + start = cur.s; |
| 37 | + end = cur.e; |
| 38 | + } |
| 39 | + cnt += end-start; // 마지막 선분 길이 업데이트 |
| 40 | + |
| 41 | + System.out.println(cnt); |
| 42 | + } |
| 43 | + static class Node implements Comparable<Node>{ |
| 44 | + int s, e; |
| 45 | + |
| 46 | + public Node(int s, int e) { |
| 47 | + this.s = s; |
| 48 | + this.e = e; |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public int compareTo(Node o) { |
| 53 | + return this.s - o.s; |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments