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
#include <algorithm>
#include <iostream>
#include <vector>

constexpr int MAX = 500000;

using namespace std;
using LL = long long;

int main()
{
    int n, c, a, w;
    cin >> n >> c;

    vector<LL> best(MAX + 1);
    vector<LL> size(MAX + 1);

    LL next_best = 0;
    int prev_size = 0;

    for (int i = 0; i < n; ++i)
    {
        cin >> a >> w;

        if (a > prev_size)
        {
            best[0] = max(best[0], next_best);
            next_best = a;
            prev_size = a;
        }

        if (size[w] == a)
            continue;

        LL tmp = max(best[w] + a, best[0] + a - c);

        best[w] = tmp;
        size[w] = a;

        next_best = max(next_best, tmp);
    }

    LL res = 0;

    for (int i = 1; i <= MAX; ++i)
    {
        res = max(res, best[i]);
    }

    cout << res << endl;

    return 0;
}