#include <bits/stdc++.h>
using namespace std;
struct item {
  int w, v, t;
};
bool operator<(item a, item b) {
  if (a.t != b.t) return a.t < b.t;
  return (a.w == b.w) ? (a.v < b.v) : (a.w < b.w);
}
struct query {
  int t, w, number;
};
bool operator<(query a, query b) { return a.t < b.t; }
int get() {
  char c;
  while (c = getchar(), (c < '0' || c > '9') && (c != '-'))
    ;
  bool flag = (c == '-');
  if (flag) c = getchar();
  int x = 0;
  while (c >= '0' && c <= '9') {
    x = x * 10 + c - 48;
    c = getchar();
  }
  return flag ? -x : x;
}
void output(int x) {
  if (x < 0) {
    putchar('-');
    x = -x;
  }
  int len = 0, data[10];
  while (x) {
    data[len++] = x % 10;
    x /= 10;
  }
  if (!len) data[len++] = 0;
  while (len--) putchar(data[len] + 48);
  putchar('\n');
}
const int maxn = 4000;
const int maxm = 4000;
const int maxq = 20000;
item a[maxn];
query q[maxq];
int f[maxn + 1][maxm + 1], g[maxn + 1][maxm + 1];
int ans[maxq];
int main() {
  int n = get(), m = get();
  for (int i = 0; i < n; i++) {
    a[i].w = get();
    a[i].v = get();
    a[i].t = get();
  }
  sort(a, a + n);
  int total = get();
  for (int i = 0; i < total; i++) {
    q[i].t = get();
    q[i].w = get();
    q[i].number = i;
  }
  sort(q, q + total);
  for (int l = 0, r = 0; l < total; l = r) {
    int W = 0;
    while (r < total && q[r].t - q[l].t < m) W = max(W, q[r++].w);
    item tmp = {-1, -1, q[l].t};
    int p0 = lower_bound(a, a + n, tmp) - a, q0 = p0;
    int p1 = upper_bound(a, a + n, tmp) - a - 1, q1 = p1;
    for (int i = 0; i <= W; i++) f[0][i] = 0;
    while (q0 < n && a[q0].t < q[l].t + m) {
      int t = q0 - p0;
      for (int i = 0; i <= W; i++) {
        f[t + 1][i] = f[t][i];
        if (i >= a[q0].w)
          f[t + 1][i] = max(f[t + 1][i], f[t][i - a[q0].w] + a[q0].v);
      }
      q0++;
    }
    for (int i = 0; i <= W; i++) g[0][i] = 0;
    while (q1 >= 0 && a[q1].t > q[l].t - m) {
      int t = p1 - q1;
      for (int i = 0; i <= W; i++) {
        g[t + 1][i] = g[t][i];
        if (i >= a[q1].w)
          g[t + 1][i] = max(g[t + 1][i], g[t][i - a[q1].w] + a[q1].v);
      }
      q1--;
    }
    for (int i = l; i < r; i++) {
      int r0 = p0, r1 = p1;
      while (r0 < n && a[r0].t <= q[i].t) r0++;
      while (r1 >= 0 && a[r1].t > q[i].t - m) r1--;
      int best = 0;
      for (int j = 0; j <= q[i].w; j++)
        best = max(best, f[r0 - p0][j] + g[p1 - r1][q[i].w - j]);
      ans[q[i].number] = best;
    }
  }
  for (int i = 0; i < total; i++) output(ans[i]);
  return 0;
}
