#include <bits/stdc++.h>
using namespace std;
struct rec1 {
  int w, v, t;
} a[4100];
struct rec2 {
  int l, r, w, id;
  bool p;
} q[21000];
bool cmp1(rec1 a, rec1 b) { return a.t < b.t; }
bool cmp2(rec2 a, rec2 b) { return a.r < b.r; }
int dp[4100][4100], n, m, ans[21000], Max = 0, p;
int bin1(int k) {
  int l = 1, r = n;
  while (l < r) {
    int mid = (l + r) / 2;
    if (a[mid].t >= k)
      r = mid;
    else
      l = mid + 1;
  }
  return l;
}
int bin2(int k) {
  int l = 1, r = n;
  while (l < r) {
    int mid = (l + r) / 2 + 1;
    if (a[mid].t <= k)
      l = mid;
    else
      r = mid - 1;
  }
  return l;
}
void solved(int l1, int r1, int l2, int r2) {
  if (l2 > r2) return;
  if (l1 == r1) {
    for (int i = l2; i <= r2; i++)
      if (q[i].l <= l1 && q[i].r >= r1 && q[i].w >= a[l1].w)
        ans[q[i].id] = a[l1].v;
    return;
  }
  int mid = (l1 + r1) / 2;
  for (int i = l1; i <= r1; i++)
    for (int j = 0; j <= Max; j++) dp[i][j] = 0;
  if (a[mid].w <= Max) dp[mid][a[mid].w] = a[mid].v;
  for (int i = 1; i <= Max; i++) dp[mid][i] = max(dp[mid][i], dp[mid][i - 1]);
  for (int i = mid - 1; i >= l1; i--) {
    for (int j = a[i].w; j <= Max; j++)
      dp[i][j] = max(dp[i + 1][j], dp[i + 1][j - a[i].w] + a[i].v);
    for (int j = a[i].w - 1; j >= 0; j--) dp[i][j] = dp[i + 1][j];
    for (int j = 1; j <= Max; j++) dp[i][j] = max(dp[i][j], dp[i][j - 1]);
  }
  if (a[mid + 1].w <= Max) dp[mid + 1][a[mid + 1].w] = a[mid + 1].v;
  for (int i = 1; i <= Max; i++)
    dp[mid + 1][i] = max(dp[mid + 1][i], dp[mid + 1][i - 1]);
  for (int i = mid + 2; i <= r1; i++) {
    for (int j = a[i].w; j <= Max; j++)
      dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - a[i].w] + a[i].v);
    for (int j = a[i].w - 1; j >= 0; j--) dp[i][j] = dp[i - 1][j];
    for (int j = 1; j <= Max; j++) dp[i][j] = max(dp[i][j], dp[i][j - 1]);
  }
  for (int i = l2; i <= r2; i++)
    if (q[i].l <= mid && q[i].r > mid && q[i].p) {
      for (int j = 0; j <= q[i].w; j++)
        ans[q[i].id] =
            max(ans[q[i].id], dp[q[i].l][j] + dp[q[i].r][q[i].w - j]);
      q[i].p = 0;
    }
  int top = l2 - 1;
  for (int i = l2; i <= r2; i++)
    if (q[i].p) q[++top] = q[i];
  if (top < l2) return;
  int tt = l2 - 1;
  while (tt < top && q[tt + 1].r <= mid) tt++;
  solved(l1, mid, l2, tt);
  solved(mid + 1, r1, tt + 1, top);
}
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++) scanf("%d%d%d", &a[i].w, &a[i].v, &a[i].t);
  sort(a + 1, a + n + 1, cmp1);
  scanf("%d", &m);
  for (int i = 1; i <= m; i++) {
    int t;
    scanf("%d%d", &t, &q[i].w);
    if (((t - p + 1) <= a[n].t) && (t >= a[1].t)) {
      q[i].l = bin1(t - p + 1);
      q[i].r = bin2(t);
      q[i].id = i;
    }
    q[i].p = ((t - p + 1) <= a[n].t) && (t >= a[1].t) && (q[i].l <= q[i].r);
    Max = max(Max, q[i].w);
  }
  sort(q + 1, q + m + 1, cmp2);
  solved(1, n, 1, m);
  for (int i = 1; i <= m; i++) printf("%d\n", ans[i]);
  return 0;
}
