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
#include <bits/stdc++.h>
using namespace std;

long long max_per_col[500005];

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

    int n, c;
    cin >> n >> c;
    int amx{};
    queue<pair<int, long long>> zm;
    int col;long long sz;
    int o_sz{};
    for(int i = 1; i <= n; i++){
        cin >> sz >> col;
        if(sz != o_sz){
            while(!zm.empty()){
                max_per_col[zm.front().first] = max(max_per_col[zm.front().first], zm.front().second);
                if(max_per_col[zm.front().first] > max_per_col[amx]){
                    amx = zm.front().first;
                }
                zm.pop();
            }
        }
        o_sz = sz;
        long long wyn = max(max_per_col[col] + sz, max_per_col[amx] + sz - c);
        wyn = max(wyn, sz);
        zm.push({col, wyn});
    }
    while(!zm.empty()){
        max_per_col[zm.front().first] = max(max_per_col[zm.front().first], zm.front().second);
        if(max_per_col[zm.front().first] > max_per_col[amx]){
            amx = zm.front().first;
        }
        zm.pop();
    }
    cout << max_per_col[amx];
}