#include <bits/stdc++.h>
using namespace std;
const int N = 4e3 + 5, T = 2e4 + 5, LG = 14 + 2;
vector<pair<int, int>> qu[T];
int n, p, c[N], h[N], t[N];
int q, dp[LG][N], ans[T];
vector<int> seg[T << 2];
void update(int x, int id = 1, int st = 0, int en = T) {
  if (t[x] + p <= st || en <= t[x]) return;
  if (t[x] <= st && en <= t[x] + p) {
    seg[id].push_back(x);
    return;
  }
  int mid = st + en >> 1;
  update(x, id << 1, st, mid);
  update(x, id << 1 | 1, mid, en);
}
void solve(int lvl = 0, int id = 1, int st = 0, int en = T) {
  for (auto x : seg[id])
    for (int i = N - 1; i >= c[x]; i--)
      dp[lvl][i] = max(dp[lvl][i], dp[lvl][i - c[x]] + h[x]);
  if (en - st == 1) {
    for (auto x : qu[st]) ans[x.second] = dp[lvl][x.first];
    return;
  }
  int mid = st + en >> 1;
  memcpy(dp[lvl + 1], dp[lvl], sizeof dp[lvl]);
  solve(lvl + 1, id << 1, st, mid);
  memcpy(dp[lvl + 1], dp[lvl], sizeof dp[lvl]);
  solve(lvl + 1, id << 1 | 1, mid, en);
}
void read_input() {
  cin >> n >> p;
  for (int i = 0; i < n; update(i++)) cin >> c[i] >> h[i] >> t[i];
  cin >> q;
  for (int i = 0; i < q; i++) {
    int a, b;
    cin >> a >> b;
    qu[a].push_back({b, i});
  }
}
void write_output() {
  for (int i = 0; i < q; i++) cout << ans[i] << endl;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  read_input(), solve(), write_output();
  return 0;
}
