#include <bits/stdc++.h>
using namespace std;
struct Item {
  int c, h, t;
  Item() {}
  Item(int c, int h, int t) : c(c), h(h), t(t) {}
  bool operator<(const Item &T) const { return t < T.t; }
} itm[4400];
int n, p, q;
int dpL[4400][4400], dpR[4400][4400];
int ans[20200];
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 0; i < n; i++) scanf("%d%d%d", &itm[i].c, &itm[i].h, &itm[i].t);
  sort(itm, itm + n);
  int pre = -1;
  for (int i = 0; i < n; i++) {
    if (itm[i].t / p != pre) {
      for (int j = itm[i].c; j <= 4000; j++) dpL[i][j] = itm[i].h;
      pre = itm[i].t / p;
    } else {
      for (int j = 0; j <= 4000; j++) dpL[i][j] = dpL[i - 1][j];
      for (int j = itm[i].c; j <= 4000; j++) {
        dpL[i][j] = max(dpL[i][j], dpL[i - 1][j - itm[i].c] + itm[i].h);
      }
    }
  }
  pre = -1;
  for (int i = n - 1; i >= 0; i--) {
    if (itm[i].t / p != pre) {
      for (int j = itm[i].c; j <= 4000; j++) dpR[i][j] = itm[i].h;
      pre = itm[i].t / p;
    } else {
      for (int j = 0; j <= 4000; j++) dpR[i][j] = dpR[i + 1][j];
      for (int j = itm[i].c; j <= 4000; j++)
        dpR[i][j] = max(dpR[i][j], dpR[i + 1][j - itm[i].c] + itm[i].h);
    }
  }
  scanf("%d", &q);
  int A, B;
  while (q--) {
    scanf("%d%d", &A, &B);
    int lid = -1, rid = -1;
    for (int i = 0; i < n; i++) {
      if (A - p + 1 <= itm[i].t && itm[i].t <= A) {
        if (lid == -1) lid = i;
        rid = i;
      }
    }
    if (lid == -1)
      printf("0\n");
    else if (itm[lid].t / p == A / p)
      printf("%d\n", dpL[rid][B]);
    else if (itm[rid].t / p == A / p - 1)
      printf("%d\n", dpR[lid][B]);
    else {
      int ans = 0;
      for (int i = 0; i <= B; i++)
        ans = max(ans, dpL[rid][i] + dpR[lid][B - i]);
      printf("%d\n", ans);
    }
  }
  return 0;
}
