#include <bits/stdc++.h>
using namespace std;
struct node {
  int c, h;
};
struct node1 {
  int t, c, id;
} q[21000];
int n, m, p, f[4100][4100], g[4100], a[4100], al, mx, ans[21000], lim;
vector<node> v1[21000], v2[21000];
bool cmp(node1 x, node1 y) {
  if (x.t < y.t) return 1;
  return 0;
}
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++) {
    int x, y, t;
    scanf("%d%d%d", &x, &y, &t);
    v1[t].push_back((node){x, y});
    v2[t + p - 1].push_back((node){x, y});
  }
  scanf("%d", &m);
  for (int i = 1; i <= m; i++) {
    scanf("%d%d", &q[i].t, &q[i].c);
    mx = max(mx, q[i].c);
    q[i].id = i;
  }
  sort(q + 1, q + m + 1, cmp);
  int l = 1, r = p, pos = 1;
  while (pos <= m) {
    while (r < q[pos].t) l += p, r += p;
    r = min(r, 21000 - 1);
    al = 0;
    for (int i = r - 1; i >= l; i--) {
      int siz = v2[i].size();
      if (siz == 0) continue;
      a[++al] = i;
      for (int j = 0; j <= mx; j++) f[al][j] = f[al - 1][j];
      for (int k = 0; k < siz; k++) {
        int c = v2[i][k].c, h = v2[i][k].h;
        for (int j = mx; j >= c; j--)
          f[al][j] = max(f[al][j], f[al][j - c] + h);
      }
    }
    for (int i = 0; i <= mx; i++) g[i] = 0;
    int las = l, now = al;
    while (pos <= m && q[pos].t <= r) {
      for (int i = las; i <= q[pos].t; i++) {
        int siz = v1[i].size();
        for (int k = 0; k < siz; k++) {
          int c = v1[i][k].c, h = v1[i][k].h;
          for (int j = mx; j >= c; j--) g[j] = max(g[j], g[j - c] + h);
        }
      }
      las = q[pos].t + 1;
      while (now && a[now] < q[pos].t) now--;
      int c = q[pos].c, tmp = 0;
      for (int i = 0; i <= c; i++) tmp = max(tmp, f[now][i] + g[c - i]);
      ans[q[pos].id] = tmp;
      pos++;
    }
  }
  for (int i = 1; i <= m; i++) printf("%d\n", ans[i]);
  return 0;
}
