#include <bits/stdc++.h>
using namespace std;
struct T {
  int c, h, t;
} a[110000];
struct T1 {
  int a, b, c;
} b[110000];
int n, q, p, to[110000], ans[110000], dp1[4001], dp[4001][4001];
bool cmp(T a, T b) { return a.t < b.t; }
bool cmp1(T1 a, T1 b) { return a.a < b.a; }
void get(int *dp1, int *dp, int a, int b) {
  for (int i = 4000; i >= 0; i--) {
    dp[i] = dp1[i];
    if (i >= a) dp[i] = max(dp[i], dp1[i - a] + b);
  }
}
void build(int l, int r, int stuffl, int stuffr, int queryl, int queryr) {
  if (stuffl > stuffr || queryl > queryr) return;
  int mid = (l + r) / 2;
  for (int i = l; i <= r; i++) to[i] = 0;
  int now = 0, i = stuffr;
  for (int j = mid; j >= l; j--) {
    while (i >= stuffl && a[i].t >= j) {
      if (a[i].t <= mid) {
        if (!now)
          get(dp1, dp[i], a[i].c, a[i].h);
        else
          get(dp[i + 1], dp[i], a[i].c, a[i].h);
        now = i;
      }
      i--;
    }
    to[j] = now;
  }
  now = 0, i = stuffl;
  for (int j = mid + 1; j <= r; j++) {
    while (i <= stuffr && a[i].t <= j) {
      if (a[i].t > mid) {
        if (!now)
          get(dp1, dp[i], a[i].c, a[i].h);
        else
          get(dp[i - 1], dp[i], a[i].c, a[i].h);
        now = i;
      }
      i++;
    }
    to[j] = now;
  }
  for (int i = queryl; i <= queryr; i++) {
    if (b[i].a == mid)
      ans[b[i].c] = dp[to[max(l, b[i].a - p + 1)]][b[i].b];
    else if (b[i].a - p + 1 == mid + 1)
      ans[b[i].c] = dp[to[min(r, b[i].a)]][b[i].b];
    else if (b[i].a - p + 1 <= mid && b[i].a > mid) {
      int X = to[max(l, b[i].a - p + 1)], Y = to[min(r, b[i].a)];
      int s = 0;
      for (int j = 0; j <= b[i].b; j++)
        s = max(s, dp[X][j] + dp[Y][b[i].b - j]);
      ans[b[i].c] = s;
    }
  }
  if (l < r) {
    if (a[stuffl].t <= mid && b[queryl].a < mid) {
      int l1 = stuffl;
      while (l1 < stuffr && a[l1 + 1].t <= mid) l1++;
      int l2 = queryl;
      while (l2 < queryr && b[l2 + 1].a < mid) l2++;
      build(l, mid, stuffl, l1, queryl, l2);
    }
    if (a[stuffr].t > mid && b[queryr].a - p + 1 > mid + 1) {
      int r1 = stuffr;
      while (r1 > stuffl && a[r1 - 1].t > mid) r1--;
      int r2 = queryr;
      while (r2 > queryl && b[r2 - 1].a - p + 1 > mid + 1) r2--;
      build(mid + 1, r, r1, stuffr, r2, queryr);
    }
  }
}
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++) scanf("%d%d%d", &a[i].c, &a[i].h, &a[i].t);
  sort(a + 1, a + n + 1, cmp);
  scanf("%d", &q);
  for (int i = 1; i <= q; i++) scanf("%d%d", &b[i].a, &b[i].b), b[i].c = i;
  sort(b + 1, b + q + 1, cmp1);
  build(1, 10000, 1, n, 1, q);
  for (int i = 1; i <= q; i++) printf("%d\n", ans[i]);
  return 0;
}
