#include <bits/stdc++.h>
using namespace std;
const int N = 2e4 + 5;
int n, p, m, q, a, b, c, h, t, w, top;
int f[N], s[25][N], ans[N];
struct node {
  int c, h, l, r;
};
vector<node> O;
vector<pair<int, int> > Q[N];
inline void insert(int c, int h) {
  for (register int i = w; i >= c; --i) f[i] = max(f[i], f[i - c] + h);
}
inline void update(void) {
  ++top;
  for (register int i = 0; i <= w; ++i) s[top][i] = f[i];
}
inline void erase(void) {
  --top;
  for (register int i = 0; i <= w; ++i) f[i] = s[top][i];
}
void solve(vector<node>& u, int l, int r) {
  vector<node> L, R;
  int mid = l + r >> 1;
  for (register vector<node>::iterator it = u.begin(); it != u.end(); ++it)
    if (l >= it->l && r <= it->r)
      insert(it->c, it->h);
    else {
      if (it->l <= mid) L.push_back(*it);
      if (it->r > mid) R.push_back(*it);
    }
  update();
  if (l == r)
    for (register vector<pair<int, int> >::iterator it = Q[l].begin();
         it != Q[l].end(); ++it)
      ans[it->second] = f[it->first];
  else
    solve(L, l, mid), solve(R, mid + 1, r);
  erase();
}
int main(void) {
  scanf("%d%d", &n, &p);
  for (register int i = 1; i <= n; ++i) {
    scanf("%d%d%d", &c, &h, &t);
    m = max(m, t + p - 1);
    O.push_back((node){c, h, t, t + p - 1});
  }
  scanf("%d", &q);
  for (register int i = 1; i <= q; ++i) {
    scanf("%d%d", &a, &b);
    w = max(w, b), m = max(m, a);
    Q[a].push_back(make_pair(b, i));
  }
  solve(O, 1, m);
  for (register int i = 1; i <= q; ++i) printf("%d\n", ans[i]);
  return 0;
}
