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

//#define DEBUG

#ifdef DEBUG
    #undef DEBUG
    #define DEBUG(x) x
#else
    #define DEBUG(x)
#endif

#define REP(x,n) for(int x=0;x<(n);++x)
#define VAR(x,n) __typeof(n) x = (n)
#define FOREACH(x,c) for(VAR(x, (c).begin()); x != (c).end(); ++x)
#define CONTAINS(x,elem) ((x).find(elem) != (x).end())

const int MAX_N = 500002;
const int MAX_M = 500002;

//highest score for tower ending with color [i]
struct BestTower {
    long long score;
    int size;
} bestForColors[MAX_M];

long long solve() {
    int n,fine;
    cin>>n>>fine;
    REP(x,n) {
    }

    /* 2 scenarios: 
        1) do not add this brick - score unchanged
        2) add this brick:
            a) to the last brick (with fine)
            b) to the highest tower containing same-color brick (without fine)
    */
    long long highestScore = 0;
    long long highestScoreForPreviousSize = 0;
    int currentSize = 0;
    int length, color;
    REP(x,n) {
        cin >> length >> color;

        if (currentSize != length) {
            currentSize = length;
            highestScoreForPreviousSize = highestScore;
        }
        BestTower& bestForColor = bestForColors[color];
        if (bestForColor.size == length) {
            DEBUG(cerr<<"skipping step "<<x<<" due to repeated brick"<<endl;)
            continue;
        }
        bestForColor.score = max(bestForColor.score + length, highestScoreForPreviousSize - fine + length);
        bestForColor.size = length;
        highestScore = max(highestScore, bestForColor.score);
        DEBUG(cerr<<"after step "<<x<<" highest score is "<<highestScoreForPreviousSize << " / "<< highestScore << endl;)
    }

    return highestScore;
}

int main() {
    ios_base::sync_with_stdio(0);
    cout << solve() << endl;
}