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
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <array>
#include <iostream>
#include <vector>

#define MAX_N 500000
#define CACHE_INIT (-1000000000000L)

class Cube {
public:
  int a;
  int w;

  Cube(int a, int w): a(a), w(w) { }
};

std::array<long long, MAX_N> cache{};

class WieSolver {
  int n{};
  int c{};
  std::vector<Cube> cubes{};

public:
  WieSolver() {
    std::cin >> n >> c;
    cubes.reserve(n);
    int a, w;
    for(int i = 0; i < n; i++) {
      std::cin >> a >> w;
      cubes.emplace_back(a, w);
    }

    std::fill_n(cache.begin(), MAX_N, CACHE_INIT);
  }

  void solve() {
    long long bestScore = getBestScore(0);
    for(int i = 1; i < cubes.size(); i++) {
      bestScore = std::max(bestScore, getBestScore(i));
    }
    std::cout << bestScore;
  }

private:
  long long getBestScore(int firstCubeIndex) {
    if(cache[firstCubeIndex] != CACHE_INIT) {
      return cache[firstCubeIndex];
    }
    int currentCubeSize = cubes[firstCubeIndex].a;
    long long bestScore = currentCubeSize;
    int nextBiggerCubeIndex = findNextBiggerCubeIndex(firstCubeIndex);
    if(nextBiggerCubeIndex == -1) {
      cache[firstCubeIndex] = bestScore;
      return bestScore;
    }
    for(int i = nextBiggerCubeIndex; i < cubes.size(); i++) {
      long long tempScore = cubes[i].w == cubes[firstCubeIndex].w ? currentCubeSize : currentCubeSize - c;
      tempScore += getBestScore(i);
      bestScore = std::max(bestScore, tempScore);
    }
    cache[firstCubeIndex] = bestScore;
    return bestScore;
  }

  int findNextBiggerCubeIndex(int cubeIndex) {
    for(int i = cubeIndex + 1; i < cubes.size(); i++) {
      if(cubes[cubeIndex].a != cubes[i].a) {
        return i;
      }
    }
    return -1;
  }
};

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

  WieSolver solver;
  solver.solve();

  return 0;
}