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

struct block {
    int size;
    int color;
};

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

    int n, c;           //blocks and penalty
    cin >> n >> c;
    vector<block> blocks(n+1);
    for(int i=0; i<n; i++) {
        int size, color;
        cin >> size >> color;
        blocks[i].size = size;
        blocks[i].color = color;
    }
    blocks[n].size = INT_MAX;           //guard

    int rainbow = 500001;           //how many colors can there be
    vector<long long int> scores(rainbow, 0);
    long long int best = 0;
    vector<bool> available(rainbow, false);
    for(int i=0; i<n; i++) {
        int end = i;
        int points = blocks[i].size;
        while(blocks[end].size == points) {
            available[blocks[end].color] = true;
            end++;
        }
        long long int tempBest = best + points - c;         //force add current block
//        best = max(best, tempBest);
        for(int j=i; j<end; j++) {          //every available block
            int color = blocks[j].color;
            if(!available[color])         //this color has already been used
                continue;
            available[color] = false;         //we use this color
            scores[color] = max(scores[color] + points, tempBest);
            best = max(scores[color], best);
        }
        i = end-1;          //after i++ i will be equal to end - next block of different size
    }
    cout << best << "\n";
    return 0;
}