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
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int n,c;
    cin>>n>>c;
    vector<long long> colour_best(500001), cur_phase(500001);
    long long best = 0;
    int prev_size = 0;
    vector<int> used;
    for (int i=0; i<n; i++) {
        int a,w;
        cin>>a>>w;

        if (prev_size!=a) {
            for (int col : used) {
                colour_best[col] = max(colour_best[col],cur_phase[col]);
                best = max(best,cur_phase[col]);
            }
            used.clear();
        }

        cur_phase[w] = max(best+a-c,colour_best[w]+a);
        prev_size = a;
        used.push_back(w);
    }

    for (int col : used) {
        colour_best[col] = max(colour_best[col],cur_phase[col]);
        best = max(best,cur_phase[col]);
    }

    cout<<best<<'\n';

    return 0;
}