#include <bits/stdc++.h>
using namespace std;
const long long MAX = 2e4 + 9;
stack<pair<long long, long long> > New;
vector<long long> start[MAX];
vector<pair<long long, long long> > query[MAX];
long long SizeNew, SizeOld, DpFirst[4003][4003], DpSecond[4003][4003];
long long N, P, W, Q, X, Y, cost[5000], value[5000], finish[MAX], res[MAX];
long long get(long long X) {
  long long res = 0;
  for (long long A = 0; A <= X; A++)
    res = max(res, DpFirst[SizeNew][A] + DpSecond[SizeOld][X - A]);
  return res;
}
void PushNew(long long val, long long cst) {
  SizeNew++;
  New.push(make_pair(val, cst));
  for (long long A = 1; A <= W; A++)
    DpFirst[SizeNew][A] = DpFirst[SizeNew - 1][A];
  for (long long A = cst; A <= W; A++)
    DpFirst[SizeNew][A] =
        max(DpFirst[SizeNew][A], val + DpFirst[SizeNew - 1][A - cst]);
  return;
}
void PushOld(long long val, long long cst) {
  SizeOld++;
  for (long long A = 1; A <= W; A++)
    DpSecond[SizeOld][A] = DpSecond[SizeOld - 1][A];
  for (long long A = cst; A <= W; A++)
    DpSecond[SizeOld][A] =
        max(DpSecond[SizeOld][A], val + DpSecond[SizeOld - 1][A - cst]);
  return;
}
void pop() {
  if (!SizeOld) {
    while (SizeNew) {
      SizeNew--;
      PushOld(New.top().first, New.top().second);
      New.pop();
    }
  }
  SizeOld--;
  return;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin >> N >> P;
  for (long long A = 1; A <= N; A++) {
    cin >> cost[A] >> value[A] >> X;
    start[X].push_back(A);
    finish[X + P]++;
    W = max(W, cost[A]);
  }
  cin >> Q;
  for (long long A = 1; A <= Q; A++) {
    cin >> X >> Y;
    query[X].push_back(make_pair(Y, A));
    W = max(W, Y);
  }
  for (long long A = 1; A <= 20000; A++) {
    for (auto B : start[A]) PushNew(value[B], cost[B]);
    while (finish[A]) {
      pop();
      finish[A]--;
    }
    for (auto B : query[A]) res[B.second] = get(B.first);
  }
  for (long long A = 1; A <= Q; A++) cout << res[A] << " ";
  return 0;
}
