#include <bits/stdc++.h>
using namespace std;
int n, p;
struct Node {
  int c, h, t;
  void input() { scanf("%d%d%d", &c, &h, &t); }
} a[4004];
int dpL[4004][4004], dpR[4004][4004];
bool cmp(const Node& a, const Node& b) { return a.t < b.t; }
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 0; i < n; i++) {
    a[i].input();
  }
  sort(a, a + n, cmp);
  for (int i = 0; i < n; i++) {
    if (i == 0 || a[i].t / p != a[i - 1].t / p) {
      for (int j = 0; j <= 4000; j++) {
        if (j >= a[i].c)
          dpL[i][j] = a[i].h;
        else
          dpL[i][j] = 0;
      }
    } else {
      for (int j = 0; j <= 4000; j++) {
        dpL[i][j] = dpL[i - 1][j];
        if (j - a[i].c >= 0)
          dpL[i][j] = max(dpL[i][j], dpL[i - 1][j - a[i].c] + a[i].h);
      }
    }
  }
  for (int i = n - 1; i >= 0; i--) {
    if (i == n - 1 || a[i].t / p != a[i + 1].t / p) {
      for (int j = 0; j <= 4000; j++) {
        if (j >= a[i].c)
          dpR[i][j] = a[i].h;
        else
          dpR[i][j] = 0;
      }
    } else {
      for (int j = 0; j <= 4000; j++) {
        dpR[i][j] = dpR[i + 1][j];
        if (j - a[i].c >= 0)
          dpR[i][j] = max(dpR[i][j], dpR[i + 1][j - a[i].c] + a[i].h);
      }
    }
  }
  int m;
  scanf("%d", &m);
  int x, y;
  int ans = 0;
  for (int i = 0; i < m; i++) {
    scanf("%d%d", &x, &y);
    int l = x - p + 1, r = x;
    int lp = -1, rp = -1;
    for (int j = 0; j < n; j++) {
      if (a[j].t > r) break;
      if (a[j].t >= l && a[j].t <= r) {
        if (lp == -1) lp = j;
        rp = j;
      }
    }
    if (lp != -1 && a[lp].t / p * p + p > r) lp = -1;
    if (rp != -1 && a[rp].t / p * p < l) rp = -1;
    ans = 0;
    for (int j = 0; j <= y; j++) {
      int now = 0;
      if (lp != -1) now += dpR[lp][j];
      if (rp != -1) now += dpL[rp][y - j];
      ans = max(ans, now);
    }
    printf("%d\n", ans);
  }
  return 0;
}
