#include <bits/stdc++.h>
using namespace std;
long long power(long long a, long long b, long long md) {
  return (!b ? 1
             : (b & 1 ? a * power(a * a % md, b / 2, md) % md
                      : power(a * a % md, b / 2, md) % md));
}
const int xn = 4e3 + 10;
const int xm = 2e4 + 10;
const int sq = 320;
const int inf = 1e9 + 10;
const long long INF = 1e18 + 10;
const int mod = 1e9 + 7;
const int base = 257;
int n, p, q, a[xm], b[xm], ans[xm], dp[2][xn][xn], res[xn];
pair<int, pair<int, int> > c[xn];
vector<pair<int, int> > adj[xm];
void build(int id, int l, int r) {
  if (r - l == 1) {
    for (pair<int, int> x : adj[l])
      if (b[x.second] >= c[l].second.first && x.first < r)
        ans[x.second] = c[l].second.second;
    return;
  }
  int mid = l + r >> 1;
  for (int i = 0; i < xn; ++i) dp[0][mid - 1][i] = 0;
  for (int i = mid; i < r; ++i) {
    for (int j = 0; j < xn; ++j) {
      dp[0][i][j] = dp[0][i - 1][j];
      if (j >= c[i].second.first)
        dp[0][i][j] = max(dp[0][i][j], dp[0][i - 1][j - c[i].second.first] +
                                           c[i].second.second);
    }
  }
  for (int i = 0; i < xn; ++i) dp[1][mid][i] = 0;
  for (int i = mid - 1; i >= l; --i) {
    for (int j = 0; j < xn; ++j) {
      dp[1][i][j] = dp[1][i + 1][j];
      if (j >= c[i].second.first)
        dp[1][i][j] = max(dp[1][i][j], dp[1][i + 1][j - c[i].second.first] +
                                           c[i].second.second);
    }
    for (pair<int, int> x : adj[i]) {
      if (x.first < mid || x.first >= r) continue;
      for (int j = 0; j <= b[x.second]; ++j)
        ans[x.second] =
            max(ans[x.second], dp[1][i][j] + dp[0][x.first][b[x.second] - j]);
    }
  }
  build(id << 1, l, mid);
  build(id << 1 | 1, mid, r);
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  cin >> n >> p;
  for (int i = 0; i < n; ++i)
    cin >> c[i].second.first >> c[i].second.second >> c[i].first;
  sort(c, c + n);
  cin >> q;
  for (int i = 1; i <= q; ++i) {
    cin >> a[i] >> b[i];
    int l = n, r = -1;
    for (int j = 0; j < n; ++j) {
      if (a[i] >= c[j].first && a[i] < c[j].first + p) l = min(l, j);
      if (a[i] >= c[j].first && a[i] < c[j].first + p) r = max(r, j);
    }
    if (r != -1) adj[l].push_back({r, i});
  }
  build(1, 0, n);
  for (int i = 1; i <= q; ++i) cout << ans[i] << '\n';
  return 0;
}
