#include <bits/stdc++.h>
struct mo {
  int x, y, z;
  bool operator<(mo _) const { return z < _.z; }
} a[4007];
int n, p, t, dp[4007][4007], Dp[4007][4007], x, y, A[4007];
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++) scanf("%d%d%d", &a[i].x, &a[i].y, &a[i].z);
  std::sort(a + 1, a + n + 1);
  for (int i = 1; i <= n; i++) A[i] = a[i].z;
  x = y = 1;
  while (y <= n) {
    while (x * p <= a[y].z) ++x;
    int w = y;
    while (y < n && a[y + 1].z < x * p) ++y;
    for (int i = w; i <= y; i++) {
      i != w ? memcpy(dp[i], dp[i - 1], sizeof dp[i]) : 0;
      for (int j = 4007 - 7; j >= a[i].x; j--)
        (dp[i][j] < dp[i][j - a[i].x] + a[i].y) &&
            (dp[i][j] = dp[i][j - a[i].x] + a[i].y);
    }
    for (int i = y; i >= w; i--) {
      i != y ? memcpy(Dp[i], Dp[i + 1], sizeof Dp[i]) : 0;
      for (int j = 4007 - 7; j >= a[i].x; j--)
        (Dp[i][j] < Dp[i][j - a[i].x] + a[i].y) &&
            (Dp[i][j] = Dp[i][j - a[i].x] + a[i].y);
    }
    ++y;
  }
  scanf("%d", &t);
  while (t--) {
    scanf("%d%d", &x, &y);
    int r = std::upper_bound(A + 1, A + n + 1, x) - A - 1;
    int l = std::lower_bound(A + 1, A + n + 1, x - p + 1) - A;
    if (l > r) {
      puts("0");
      continue;
    }
    if (a[r].z / p == a[l].z / p)
      printf("%d\n", a[r].z / p == x / p ? dp[r][y] : Dp[l][y]);
    else {
      int ans = 0;
      for (int i = 0; i <= y; i++)
        (ans < dp[r][i] + Dp[l][y - i]) && (ans = dp[r][i] + Dp[l][y - i]);
      printf("%d\n", ans);
    }
  }
  return 0;
}
