#include <bits/stdc++.h>
using namespace std;
int n, p, c, h, t, head[100005], Next[200005], adjc[200005], adjh[200005], q, a,
    b, f[4005], k, i;
int qhead[100005], qNext[200005], qadj[200005], num[200005], ans[100005];
void Push(int u, int c, int h) {
  Next[++k] = head[u];
  head[u] = k;
  adjc[k] = c;
  adjh[k] = h;
}
void qPush(int u, int v, int w) {
  qNext[++k] = qhead[u];
  qhead[u] = k;
  qadj[k] = v;
  num[k] = w;
}
void modify(int i, int l, int r, int ll, int rr, int c, int h) {
  if (l >= ll && r <= rr) {
    Push(i, c, h);
    return;
  }
  int mid = l + r >> 1;
  if (mid >= ll) modify(i << 1, l, mid, ll, rr, c, h);
  if (mid < rr) modify(i << 1 | 1, mid + 1, r, ll, rr, c, h);
}
void Query(int i, int l, int r) {
  int j, k;
  for (j = head[i]; j != 0; j = Next[j])
    for (k = 4000; k >= adjc[j]; k--)
      f[k] = max(f[k], f[k - adjc[j]] + adjh[j]);
  if (l == r) {
    for (j = qhead[l]; j != 0; j = qNext[j]) ans[num[j]] = f[qadj[j]];
    return;
  }
  int tmp[4005];
  memcpy(tmp, f, sizeof(tmp));
  int mid = l + r >> 1;
  Query(i << 1, l, mid);
  memcpy(f, tmp, sizeof(f));
  Query(i << 1 | 1, mid + 1, r);
}
int main() {
  scanf("%d %d", &n, &p);
  for (i = 1; i <= n; i++) {
    scanf("%d %d %d", &c, &h, &t);
    modify(1, 1, 20000, t, t + p - 1, c, h);
  }
  scanf("%d", &q);
  k = 0;
  for (i = 1; i <= q; i++) {
    scanf("%d %d", &a, &b);
    qPush(a, b, i);
  }
  Query(1, 1, 20000);
  for (i = 1; i <= q; i++) printf("%d\n", ans[i]);
}
