#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int s = 0, t = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') t = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9')
    s = (s << 3) + (s << 1) + (ch ^ 48), ch = getchar();
  return s * t;
}
const int N = 4005;
const int M = 20005;
const int Siz = 4000;
int n, m, T;
int fr[N], fl[N][N], Ans[M];
struct Node {
  int v, w, t;
} p[N], q[M];
bool cmp(Node A, Node B) { return A.t < B.t; }
void Ins(int k) {
  for (int i = Siz; i >= p[k].v; i--)
    fr[i] = max(fr[i], fr[i - p[k].v] + p[k].w);
}
void Build(int l, int r) {
  memset(fr, 0, sizeof(fr));
  for (int k = r; k >= l; k--)
    for (int i = Siz; i >= 0; i--) {
      fl[k][i] = fl[k + 1][i];
      if (i >= p[k].v) fl[k][i] = max(fl[k][i], fl[k + 1][i - p[k].v] + p[k].w);
    }
}
int main() {
  n = read(), T = read();
  for (int i = 1; i <= n; i++) p[i] = (Node){read(), read(), read()};
  sort(p + 1, p + n + 1, cmp);
  m = read();
  for (int i = 1; i <= m; i++) {
    int x = read(), v = read();
    q[i] = (Node){v, i, x - T + 1};
  }
  sort(q + 1, q + m + 1, cmp);
  int l = 1, r = 0, mid = 0;
  for (int i = 1; i <= m; i++) {
    while (r + 1 <= n && p[r + 1].t <= q[i].t + T - 1) Ins(++r);
    while (l <= r && p[l].t < q[i].t) l++;
    if (l > mid) Build(l, r), mid = r;
    for (int j = 0, res = 0; j <= q[i].v; j++) {
      res = max(res, fr[j]);
      Ans[q[i].w] = max(Ans[q[i].w], res + fl[l][q[i].v - j]);
    }
  }
  for (int i = 1; i <= m; i++) cout << Ans[i] << '\n';
  return 0;
}
