#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const int M = 4005;
struct node {
  int c, h, t;
  bool operator<(const node &a) const { return t < a.t; }
} d[M];
int L[M][M], R[M][M];
int Max(int &x, int y) {
  if (x < y) x = y;
}
int main() {
  int n, p;
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++) scanf("%d%d%d", &d[i].c, &d[i].h, &d[i].t);
  sort(d + 1, d + n + 1);
  for (int last = -1, i = 1; i <= n; i++) {
    if (last != d[i].t / p) {
      for (int j = 4000; j >= d[i].c; j--) L[i][j] = d[i].h;
    } else {
      for (int j = 4000; j >= d[i].c; j--)
        L[i][j] = max(L[i - 1][j], L[i - 1][j - d[i].c] + d[i].h);
      for (int j = d[i].c - 1; j >= 0; j--) L[i][j] = L[i - 1][j];
    }
    last = d[i].t / p;
  }
  for (int last = -1, i = n; i >= 1; i--) {
    if (last != d[i].t / p) {
      for (int j = 4000; j >= d[i].c; j--) R[i][j] = d[i].h;
    } else {
      for (int j = 4000; j >= d[i].c; j--)
        R[i][j] = max(R[i + 1][j], R[i + 1][j - d[i].c] + d[i].h);
      for (int j = d[i].c - 1; j >= 0; j--) R[i][j] = R[i + 1][j];
    }
    last = d[i].t / p;
  }
  int m;
  scanf("%d", &m);
  for (int u, v, i = 1; i <= m; i++) {
    scanf("%d%d", &u, &v);
    int l = n + 1, r = -1;
    for (int j = 1; j <= n; j++) {
      if (d[j].t > u - p) {
        l = j;
        break;
      }
    }
    for (int j = n; j >= 1; j--) {
      if (d[j].t <= u) {
        r = j;
        break;
      }
    }
    if (l > r) {
      puts("0");
      continue;
    }
    if (d[l].t / p == d[r].t / p) {
      if (u / p == d[l].t / p)
        printf("%d\n", L[r][v]);
      else
        printf("%d\n", R[l][v]);
      continue;
    }
    int ans = 0;
    for (int i = 0; i <= v; i++) Max(ans, R[l][i] + L[r][v - i]);
    printf("%d\n", ans);
  }
  return 0;
}
