[Link] https://www.acmicpc.net/problem/2836
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
50
51
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader br;
static StringBuilder sb = new StringBuilder();
static int[] seg;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
sb = new StringBuilder();
int[] arr = getArr();
int n = arr[0], m = arr[1];
ArrayList<Line> lines = new ArrayList<>();
int incLeft = m, incRight = 0, decLeft = m, decRight = 0;
while(n-- > 0) {
arr = getArr();
int pos = arr[0], dest = arr[1];
if(dest < pos) lines.add(new Line(dest, pos));
}
if(lines.isEmpty()) {
print(m);
return;
}
Collections.sort(lines, (l, r) -> l.left > r.left ? 1 : -1 );
int preRight = lines.get(0).right, dis = preRight - lines.get(0).left;
for(int i = 1; i < lines.size(); i++) {
Line line = lines.get(i);
if(line.right <= preRight) continue;
if(preRight <= line.left) dis += line.right - line.left;
else dis += line.right - preRight;
preRight = line.right;
}
print(m + 2 * (long)dis);
}
static class Line {
int left, right;
Line(int left, int right) { this.left = left; this.right = right; }
}
static int toi(String s) { return Integer.parseInt(s); }
static long tol(String s) { return Long.parseLong(s); }
static String[] getLine() throws IOException { return br.readLine().split(" "); }
static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
static <T> void print(T s) { System.out.print(s); }
static <T> void println(T s) { System.out.println(s); }
}