#include <bits/stdc++.h>
using namespace std;
const int MAXN = 4e3 + 10;
const int MAXT = 2e4 + 10;
const int MAXQ = 2e4 + 10;
const int MAXB = 4e3 + 10;
struct Node {
  int t, c, h;
  bool operator<(const Node& a) const { return t < a.t; }
} item[MAXN];
struct QNode {
  int t, b, id;
  bool operator<(const QNode& a) const { return t < a.t; }
} que[MAXQ];
int n, P, m;
int ans[MAXQ];
int dpl[MAXN][MAXB], dpr[MAXN][MAXB];
void Gao(int T, int& mid, int& q) {
  while (mid < n && item[mid].t <= T) ++mid;
  int nl = 0, nr = 0;
  for (int i = mid - 1; i >= 0 && item[i].t > T - P; --i) {
    ++nl;
    for (int j = 1; j < MAXB; ++j) {
      dpl[nl][j] = max(dpl[nl][j - 1], dpl[nl - 1][j]);
      if (j >= item[i].c)
        dpl[nl][j] = max(dpl[nl][j], dpl[nl - 1][j - item[i].c] + item[i].h);
    }
  }
  for (int i = mid; i < n && item[i].t < T + P; ++i) {
    ++nr;
    for (int j = 1; j < MAXB; ++j) {
      dpr[nr][j] = max(dpr[nr][j - 1], dpr[nr - 1][j]);
      if (j >= item[i].c)
        dpr[nr][j] = max(dpr[nr][j], dpr[nr - 1][j - item[i].c] + item[i].h);
    }
  }
  int lp = nl, rp = 0;
  for (; q < m && que[q].t < T + P; ++q) {
    int id = que[q].id, b = que[q].b;
    while (lp > 0 && item[mid - lp].t <= que[q].t - P) --lp;
    while (rp < nr && item[mid + rp].t <= que[q].t) ++rp;
    for (int j = 0; j <= b; ++j) {
      ans[id] = max(ans[id], dpl[lp][j] + dpr[rp][b - j]);
    }
  }
}
int main() {
  cin >> n >> P;
  for (int i = 0; i < (n); i++) {
    scanf("%d%d%d", &item[i].c, &item[i].h, &item[i].t);
  }
  sort(item, item + n);
  cin >> m;
  for (int i = 0; i < (m); i++) {
    scanf("%d%d", &que[i].t, &que[i].b);
    que[i].id = i;
  }
  sort(que, que + m);
  int maxt = que[m - 1].t;
  int mid = 0, q = 0;
  for (int i = 1; i <= maxt; i += P) {
    Gao(i, mid, q);
  }
  for (int i = 0; i < (m); i++) {
    printf("%d\n", ans[i]);
  }
  return 0;
}
