#include <bits/stdc++.h>
using namespace std;
int n, p, m, B = 4000;
struct node {
  int c, h, t;
} a[4010];
struct Node {
  int dp[4010];
  int x, nex;
} f[8010];
int fir[40010], tot;
void add(int u, int x) {
  f[++tot].nex = fir[u];
  for (int i = 0; i <= B; i++) {
    if (i >= a[x].c)
      f[tot].dp[i] = max(f[fir[u]].dp[i], f[fir[u]].dp[i - a[x].c] + a[x].h);
    else
      f[tot].dp[i] = f[fir[u]].dp[i];
  }
  f[tot].x = a[x].t;
  fir[u] = tot;
}
bool cmp(node a, node b) { return a.t < b.t; }
int main() {
  cin >> n >> p;
  for (int i = 1; i <= n; i++) {
    cin >> a[i].c >> a[i].h >> a[i].t;
  }
  sort(a + 1, a + n + 1, cmp);
  m = a[n].t / p;
  int k = 0;
  for (int i = 1; i <= n; i++) {
    add((a[i].t / p) * 2 + 1, i);
  }
  for (int i = n; i >= 1; i--) {
    add((a[i].t / p + 1) * 2, i);
  }
  int T;
  cin >> T;
  int a, b;
  while (T--) {
    cin >> a >> b;
    int ans = 0;
    int l = 0, r = 0, exp;
    exp = a / p;
    for (int i = fir[exp * 2]; i; i = f[i].nex) {
      if (f[i].x >= a - p + 1) {
        l = i;
        break;
      }
    }
    for (int i = fir[exp * 2 + 1]; i; i = f[i].nex) {
      if (f[i].x <= a) {
        r = i;
        break;
      }
    }
    for (int i = 0; i <= b; i++) {
      ans = max(ans, f[l].dp[i] + f[r].dp[b - i]);
    }
    cout << ans << endl;
  }
  return 0;
}
