#include <bits/stdc++.h>
#pragma GCC optimize("O2")
#pragma GCC optimize("unroll-loops")
using namespace std;
const long double eps = 1e-7;
const int inf = 1000000010;
const long long INF = 10000000000000010LL;
const int mod = 1000000007;
const int MAXN = 20010, N = 4001;
int n, p, q, k, u, v, x, y, t, a, b, c, h;
int ans[MAXN];
array<int, N> dp[20];
vector<pair<int, int> > seg[MAXN << 2], Q[MAXN];
void Add(int id, int tl, int tr, int l, int r, pair<int, int> val) {
  if (r <= tl || tr <= l) return;
  if (l <= tl && tr <= r) {
    seg[id].push_back(val);
    return;
  }
  int mid = (tl + tr) >> 1;
  Add(id << 1, tl, mid, l, r, val);
  Add(id << 1 | 1, mid, tr, l, r, val);
}
void dfs(int id, int tl, int tr, int depth) {
  for (pair<int, int> p : seg[id]) {
    int c = p.first, h = p.second;
    for (int i = N - 1; i >= c; i--)
      dp[depth][i] = max(dp[depth][i], dp[depth][i - c] + h);
  }
  if (tr - tl == 1) {
    for (pair<int, int> p : Q[tl]) ans[p.second] = dp[depth][p.first];
    return;
  }
  int mid = (tl + tr) >> 1;
  dp[depth + 1] = dp[depth];
  dfs(id << 1, tl, mid, depth + 1);
  dp[depth + 1] = dp[depth];
  dfs(id << 1 | 1, mid, tr, depth + 1);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> p;
  while (n--) {
    cin >> c >> h >> t;
    Add(1, 0, MAXN, t, t + p, {c, h});
  }
  cin >> q;
  for (int i = 1; i <= q; i++) {
    cin >> a >> b;
    Q[a].push_back({b, i});
  }
  dfs(1, 0, MAXN, 0);
  for (int i = 1; i <= q; i++) cout << ans[i] << '\n';
  return 0;
}
