#include <bits/stdc++.h>
using namespace std;
const int N = 20005;
const int len = 400;
const int mod = 1e9 + 7;
int n, p, q, ans[N];
struct node {
  int c, h, t;
} a[N];
vector<int> all, in[N * 4];
vector<pair<int, int> > lazy[N];
void upd(int l, int r, int x, int v = 1, int tl = 0, int tr = all.size() - 1) {
  if (tl > r || tr < l || l > r) return;
  if (l <= tl && tr <= r) {
    in[v].push_back(x);
    return;
  }
  int tm = (tl + tr) / 2;
  upd(l, r, x, v * 2, tl, tm);
  upd(l, r, x, v * 2 + 1, tm + 1, tr);
}
void solve(vector<int> now, int v = 1, int tl = 0, int tr = all.size() - 1) {
  for (auto id : in[v]) {
    for (int i = 4000; i >= 0; i--) {
      if (i - a[id].c >= 0) {
        now[i] = max(now[i], now[i - a[id].c] + a[id].h);
      }
    }
  }
  if (tl == tr) {
    for (auto i : lazy[all[tl]]) {
      int id = i.second;
      int w = i.first;
      ans[id] = now[w];
    }
    return;
  }
  int tm = (tl + tr) / 2;
  solve(now, v * 2, tl, tm);
  solve(now, v * 2 + 1, tm + 1, tr);
}
int main() {
  ios_base::sync_with_stdio(0);
  cin >> n >> p;
  for (int i = 1; i <= n; i++) {
    cin >> a[i].c >> a[i].h >> a[i].t;
  }
  cin >> q;
  for (int i = 1; i <= q; i++) {
    int x, y;
    cin >> x >> y;
    all.push_back(x);
    lazy[x].push_back(make_pair(y, i));
  }
  sort(all.begin(), all.end());
  all.resize(unique(all.begin(), all.end()) - all.begin());
  for (int i = 1; i <= n; i++) {
    int l = lower_bound(all.begin(), all.end(), a[i].t) - all.begin();
    int r =
        upper_bound(all.begin(), all.end(), a[i].t + p - 1) - all.begin() - 1;
    if (l <= r) upd(l, r, i);
  }
  vector<int> now;
  now.resize(4001);
  solve(now);
  for (int i = 1; i <= q; i++) cout << ans[i] << endl;
  return 0;
}
