#include <bits/stdc++.h>
using namespace std;
const int maxn = 4001, N = 20001;
int d[10001][maxn], cat[maxn], c[maxn], h[maxn], C[N], ans[N], n, p;
vector<int> G[N];
vector<int> qry[N];
void gao(int x) {
  int l = max(1, x - p + 1), r = min(20000, x + p - 1);
  memset(cat, 0, sizeof(cat));
  int mx = 0;
  for (int i = x - 1, cur = 1; i >= l; i--, cur++) {
    for (auto id : G[i])
      for (int j = 4000; j >= c[id]; j--)
        cat[j] = max(cat[j], cat[j - c[id]] + h[id]);
    memcpy(d[cur], cat, sizeof(cat));
    mx = cur;
  }
  memset(cat, 0, sizeof(cat));
  for (int i = x, cur = 1; i <= r; i++, cur++) {
    for (auto id : G[i])
      for (int j = 4000; j >= c[id]; j--)
        cat[j] = max(cat[j], cat[j - c[id]] + h[id]);
    for (auto id : qry[i]) {
      int pre = min(mx, p - cur);
      for (int j = 0; j <= C[id]; j++)
        ans[id] = max(ans[id], d[pre][j] + cat[C[id] - j]);
    }
  }
}
int main() {
  int q, t;
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++) {
    scanf("%d%d%d", &c[i], &h[i], &t);
    G[t].push_back(i);
  }
  scanf("%d", &q);
  for (int i = 1; i <= q; i++) {
    scanf("%d%d", &t, &C[i]);
    qry[t].push_back(i);
  }
  for (int i = 1; i <= 20000; i += p) gao(i);
  for (int i = 1; i <= q; i++) printf("%d\n", ans[i]);
}
