Problem: Example

Input

2 10
10 200 1
10 100 100


Output

200

Solution (in CPP):

Solution:
#include<bits/stdc++.h>
 
using namespace std;
 
template< class T >
struct ConvexHullTrickAddQueryMonotone
{
  deque< pair< T, T > > L;
  int isdec;
 
  ConvexHullTrickAddQueryMonotone() : isdec(-1) {}
 
  inline T getX(const pair< T, T > &a, const T &x)
  {
    return (a.first * x + a.second);
  }
 
  inline bool check(const pair< T, T > &a, const pair< T, T > &b, const pair< T, T > &c)
  {
    return ((b.first - a.first) * (c.second - b.second) >= (b.second - a.second) * (c.first - b.first));
  }
 
  inline bool empty() { return (L.empty()); }
 
  void add(T a, T b)
  {
    pair< T, T > line(a, b);
 
    if(!L.empty() && L.back().first == a) {
      line.second = min(line.second, L.back().second);
      L.pop_back();
    }
    while(L.size() >= 2 && check(L[L.size() - 2], L.back(), line)) L.pop_back();
    L.emplace_back(line);
 
  }
 
  T getMinimumQuery(T x)
  {
    int low = -1, high = (int) L.size() - 1;
    while(high - low > 1) {
      int mid = (low + high) >> 1;
      if((getX(L[mid], x) >= getX(L[mid + 1], x))) low = mid;
      else high = mid;
    }
    return (getX(L[high], x));
  }
 
  T getMinimumQueryMonotone(T x)
  {
    while(L.size() >= 2 && getX(L[0], x) >= getX(L[1], x)) {
      L.pop_front();
    }
    return (getX(L[0], x));
  }
 
};
 
using int64 = long long;
const int64 INF = 1LL << 62;
 
int N, T;
vector< tuple< int, int, int > > dd;
int64 dp[4001][4001];
int64 t[4000], p[4000], f[4000];
 
int main()
{
  scanf("%d %d", &N, &T);
  for(int i = 0; i < N; i++) {
    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);
    if(a <= T) dd.emplace_back(c, a, b);
  }
  sort(begin(dd), end(dd));
  N = (int) dd.size();
  for(int i = 0; i < N; i++) {
    tie(f[i], t[i], p[i]) = dd[i];
  }
 
  fill_n(*dp, 4001 * 4001, -INF);
  vector< ConvexHullTrickAddQueryMonotone< int64 > > cht(T + 1, ConvexHullTrickAddQueryMonotone< int64 >());
 
  for(int i = 0; i < N; i++) {
    dp[i][t[i]] = p[i];
    for(int j = T; j >= t[i]; j--) {
      if(cht[j - t[i]].empty()) continue;
      dp[i][j] = max(dp[i][j], -cht[j - t[i]].getMinimumQueryMonotone(f[i]) + p[i] - f[i] * f[i]);
    }
    for(int j = T; j >= 0; j--) {
      if(dp[i][j] == -INF) continue;
      cht[j].add(-2 * f[i], -(dp[i][j] - f[i] * f[i]));
    }
  }
 
  int64 ret = 0;
  for(int i = 0; i < N; i++) {
    for(int j = 0; j <= T; j++) {
      ret = max(ret, dp[i][j]);
    }
  }
  printf("%lld\n", ret);
}