#include <bits/stdc++.h>
using namespace std;
const int MAX_COST = 4000;
struct Update {
  int cost, profit;
  Update(int cost, int profit) : cost(cost), profit(profit) {}
};
struct CommutativeUndoableDS {
  vector<array<int, MAX_COST + 1> > stk;
  CommutativeUndoableDS() {
    stk.emplace_back();
    fill(stk.back().begin(), stk.back().end(), 0);
  }
  void addUpdate(Update u) {
    int sz = stk.size();
    stk.push_back(stk.back());
    for (int i = MAX_COST; i >= u.cost; i--) {
      stk[sz][i] = max(stk[sz][i], stk[sz - 1][i - u.cost] + u.profit);
    }
  }
  void undoLastUpdate() {
    stk.pop_back();
    assert(!stk.empty());
  }
  int bestProfitWith(int budget) { return stk.back()[budget]; }
};
struct QueueUndoDS {
  vector<pair<Update, int> > qyu;
  CommutativeUndoableDS ds;
  int rem_a;
  QueueUndoDS() { rem_a = 0; }
  void pushBack(pair<Update, int> u) {
    ds.addUpdate(u.first);
    qyu.emplace_back(u);
  }
  void pushBack(Update u) { pushBack(pair<Update, int>(u, 1)); }
  void popFront() {
    assert(!qyu.empty());
    if (rem_a == 0) {
      rem_a = qyu.size();
      for (int i = 0; i < rem_a; i++) ds.undoLastUpdate();
      reverse(qyu.begin(), qyu.end());
      for (pair<Update, int> &u : qyu) {
        u.second = 0;
        ds.addUpdate(u.first);
      }
    }
    vector<pair<Update, int> > popped[2];
    while (qyu.back().second == 1) {
      popped[1].push_back(qyu.back());
      qyu.pop_back();
      ds.undoLastUpdate();
    }
    int sz = rem_a & (-rem_a);
    for (int i = 0; i < sz; i++) {
      assert(qyu.back().second == 0);
      popped[0].push_back(qyu.back());
      qyu.pop_back();
      ds.undoLastUpdate();
    }
    for (int z : {1, 0}) {
      reverse(popped[z].begin(), popped[z].end());
      for (pair<Update, int> &u : popped[z]) pushBack(u);
    }
    assert(qyu.back().second == 0);
    ds.undoLastUpdate();
    qyu.pop_back();
    rem_a--;
  }
};
const int MAX_TIME = 20001;
vector<Update> startsAt[MAX_TIME];
vector<Update> endsAt[MAX_TIME];
vector<pair<int, int> > askAt[MAX_TIME];
int ans[MAX_TIME];
int main() {
  int n, p;
  cin >> n >> p;
  while (n--) {
    int c, h, t;
    cin >> c >> h >> t;
    startsAt[t].emplace_back(c, h);
    endsAt[t + p - 1].emplace_back(c, h);
  }
  int q;
  cin >> q;
  for (int i = 1; i <= q; i++) {
    int a, b;
    cin >> a >> b;
    askAt[a].emplace_back(i, b);
  }
  QueueUndoDS knapsackQueuUndo;
  for (int t = 1; t < MAX_TIME; t++) {
    for (Update u : startsAt[t]) {
      knapsackQueuUndo.pushBack(u);
    }
    for (pair<int, int> query : askAt[t]) {
      ans[query.first] = knapsackQueuUndo.ds.bestProfitWith(query.second);
    }
    for (Update u : endsAt[t]) {
      knapsackQueuUndo.popFront();
    }
  }
  for (int i = 1; i <= q; i++) {
    cout << ans[i] << "\n";
  }
  return 0;
}
