#include <bits/stdc++.h>
using namespace std;
struct node {
  int c, h, t;
} a[4002];
bool cmp(node a, node b) { return a.t < b.t; }
int dp[2][4005][4005];
int L[10005], R[10005];
int main() {
  int n, p;
  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);
  int j = 1;
  int mx = (a[n].t + p - 1) / p * p;
  for (int i = 1; i <= mx; i += p) {
    for (; j <= n; j++) {
      if (a[j].t >= i + p) break;
      for (int k = 4000; k >= 1; k--) {
        if (a[j - 1].t >= i) {
          if (k >= a[j].c)
            dp[0][j][k] =
                max(dp[0][j - 1][k], dp[0][j - 1][k - a[j].c] + a[j].h);
          else
            dp[0][j][k] = dp[0][j - 1][k];
        } else if (k >= a[j].c)
          dp[0][j][k] = dp[0][j][k - a[j].c] + a[j].h;
      }
    }
    int pos = j - 1;
    for (; pos >= 1; pos--) {
      if (a[pos].t < i) break;
      for (int k = 4000; k >= 1; k--) {
        if (a[pos + 1].t < i + p) {
          if (k >= a[pos].c)
            dp[1][pos][k] =
                max(dp[1][pos + 1][k], dp[1][pos + 1][k - a[pos].c] + a[pos].h);
          else
            dp[1][pos][k] = dp[1][pos + 1][k];
        } else if (k >= a[pos].c)
          dp[1][pos][k] = dp[1][pos][k - a[pos].c] + a[pos].h;
      }
    }
  }
  j = 1;
  for (int i = 1; i <= n; i++)
    for (; j <= a[i].t; j++)
      if ((j + p - 1) / p * p >= a[i].t) R[j] = i;
  j = 10000;
  for (int i = n; i >= 1; i--)
    for (; j >= a[i].t; j--)
      if ((j + p - 1) / p * p - p + 1 <= a[i].t) L[j] = i;
  int Q;
  scanf("%d", &Q);
  for (int i = 0; i < Q; i++) {
    int u, v;
    scanf("%d%d", &u, &v);
    if (u - p + 1 > a[n].t) {
      printf("0\n");
      continue;
    }
    int ans = 0;
    int l = max(1, u - p + 1);
    int r = min(u, a[n].t);
    if (l > r) {
      printf("0\n");
      continue;
    }
    if ((l + p - 1) % p == 0 || r % p == 0) {
      printf("%d\n", dp[0][L[r]][v]);
      continue;
    }
    if (r == a[n].t && (l + p - 1) / p == (r + p - 1) / p) {
      printf("%d\n", dp[1][R[l]][v]);
      continue;
    }
    for (j = 0; j <= v; j++)
      ans = max(ans, dp[0][L[r]][j] + dp[1][R[l]][v - j]);
    printf("%d\n", ans);
  }
  return 0;
}
