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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <vector>
#include <utility>
#include <unordered_map>
#include <queue>
#include <limits.h>

using namespace std;

void input(int & n, long long & c, vector<pair<long long, long long>> & blocks) {
    cin >> n >> c;
    blocks.resize(n);
    for(int i = n-1; i >= 0; i--) {
        cin >> blocks[i].first >> blocks[i].second;
    }
}

long long get_result(long long const & c, vector<pair<long long, long long>> const & blocks) {
    unordered_map<long long, long long> best_color_tower;
    pair<long long, int> best_tower{};
    long long last_width = INT_MAX;
    queue<pair<long long, int>> width_que;
    for(auto const & el : blocks) {
        if(el.first != last_width) {
            last_width = el.first;
            pair<long long, int> cur_el{};
            while(!width_que.empty()) {
                cur_el = width_que.front();
                width_que.pop();
                if(best_tower.first < cur_el.first) {
                    best_tower = cur_el;
                }
                if(best_color_tower[cur_el.second] < cur_el.first) {
                    best_color_tower[cur_el.second] = cur_el.first;
                }
            }
        }
        long long cur_top = best_color_tower[el.second] + el.first;
        if(best_tower.second != el.second && (best_tower.first - c + el.first > cur_top)) {
            cur_top = best_tower.first - c + el.first;
        }
        width_que.push({cur_top, el.second});
    } 
    pair<long long, int> cur_el{};
    while(!width_que.empty()) {
        cur_el = width_que.front();
        width_que.pop();
        if(best_tower.first < cur_el.first) {
            best_tower = cur_el;
        }
        if(best_color_tower[cur_el.second] < cur_el.first) {
            best_color_tower[cur_el.second] = cur_el.first;
        }
    }
    return best_tower.first;
}

void solve() {
    int n;
    long long c;
    vector<pair<long long, long long>> blocks;

    input(n, c, blocks);

    cout << get_result(c, blocks) << "\n";
}

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    solve();

    return 0;
}