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
n, c = [int(x) for x in input().split(' ')]
last_size = 0
blocks = []
colors = {}
for _ in range(n):
    a, w = [int(x) for x in input().split(' ')]
    if a == last_size:
        blocks[-1][1].add(w)
    else:
        blocks.append([a, {w}])
        last_size = a
    if w not in colors:
        colors[w] = 0
blocks.reverse()

best_color = None
best_color_size = 0
for size, size_blocks in blocks:
    partial = []
    for w in size_blocks:
        if not best_color:
            o = size
        elif best_color == w:
            o = colors[w] + size
        else:
            o1 = best_color_size + size - c
            o2 = colors[w] + size
            o = max(o1, o2)
        colors[w] = o
        partial.append([o, w])
    partial.sort(reverse=True)
    if partial[0][0] > best_color_size:
        best_color = partial[0][1]
        best_color_size = partial[0][0]
    #print(size, colors)
    #print(partial, best_color)
print(colors[best_color])