#include <bits/stdc++.h>
using namespace std;
int gi() {
  int x = 0, o = 1;
  char ch = getchar();
  while (!isdigit(ch) && ch != '-') ch = getchar();
  if (ch == '-') o = -1, ch = getchar();
  while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
  return x * o;
}
int n, p, dp[4010], ans[20010], q;
vector<pair<int, int> > vec[100010], qry[20010];
void insert(int L, int R, pair<int, int> v, int x = 1, int l = 1, int r = 2e4) {
  if (L <= l && r <= R) {
    vec[x].push_back(v);
    return;
  }
  int mid = (l + r) >> 1;
  if (L <= mid) insert(L, R, v, (x << 1), l, mid);
  if (R > mid) insert(L, R, v, (x << 1 | 1), mid + 1, r);
}
void add(pair<int, int> t) {
  for (int i = 4000; i >= t.first; i--)
    dp[i] = max(dp[i], dp[i - t.first] + t.second);
}
void solve(int x = 1, int l = 1, int r = 2e4) {
  int pre[4010];
  memcpy(pre, dp, sizeof(dp));
  for (auto t : vec[x]) add(t);
  if (l == r) {
    for (auto t : qry[l]) ans[t.second] = *max_element(dp, dp + t.first + 1);
  } else {
    int mid = (l + r) >> 1;
    solve((x << 1), l, mid);
    solve((x << 1 | 1), mid + 1, r);
  }
  memcpy(dp, pre, sizeof(dp));
}
int main() {
  cin >> n >> p;
  for (int i = 1; i <= n; i++) {
    int c = gi(), h = gi(), t = gi();
    insert(t, t + p - 1, make_pair(c, h));
  }
  cin >> q;
  for (int i = 1; i <= q; i++) {
    int a = gi(), b = gi();
    qry[a].push_back(make_pair(b, i));
  }
  memset(dp, 0xc0, sizeof(dp));
  dp[0] = 0;
  solve();
  for (int i = 1; i <= q; i++) cout << ans[i] << '\n';
  return 0;
}
