#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e4 + 10, Max = 4e3 + 10, mod = 1e9 + 7;
const long long inf = 1e18;
template <typename A, typename B>
ostream& operator<<(ostream& out, pair<A, B> p) {
  out << "{ " << p.first << ", " << p.second << " }";
  return out;
}
template <typename T>
ostream& operator<<(ostream& out, vector<T> v) {
  out << "[ ";
  for (int i = 0; i < int((v).size()); i++) {
    out << v[i];
    if (i != int((v).size()) - 1) out << " ,";
  }
  out << " ]";
  return out;
}
vector<pair<int, int> > tdo[4 * maxn];
vector<pair<int, int> > qur[maxn];
int ans[maxn];
void add(int f, int s, pair<int, int> p, int l = 0, int r = maxn, int id = 1) {
  if (f >= s || l >= r || s <= l || r <= f) return;
  if (f <= l && r <= s) {
    tdo[id].push_back(p);
    return;
  }
  int mid = (l + r) >> 1;
  add(f, s, p, l, mid, 2 * id);
  add(f, s, p, mid, r, 2 * id + 1);
}
int dp[Max];
vector<pair<int, int> > fback;
void solve(int l = 0, int r = maxn, int id = 1) {
  for (pair<int, int> p : tdo[id]) {
    for (int i = Max - 1; i >= 0; i--) {
      if (i >= p.first && dp[i - p.first] + p.second > dp[i])
        fback.push_back({i, dp[i]}), dp[i] = dp[i - p.first] + p.second;
    }
  }
  if (r - l == 1) {
    for (pair<int, int> p : qur[l]) ans[p.second] = dp[p.first];
    return;
  }
  int mid = (l + r) >> 1;
  int SZ = int((fback).size());
  solve(l, mid, 2 * id);
  while (int((fback).size()) > SZ) {
    dp[fback.back().first] = fback.back().second;
    fback.pop_back();
  }
  solve(mid, r, 2 * id + 1);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie();
  int n, p;
  cin >> n >> p;
  for (int i = 0; i < n; i++) {
    int c, h, t;
    cin >> c >> h >> t;
    add(t, t + p, (pair<int, int>){c, h});
  }
  int q;
  cin >> q;
  for (int i = 0; i < q; i++) {
    int t, c;
    cin >> t >> c;
    qur[t].push_back({c, i});
  }
  solve();
  for (int i = 0; i < q; i++) cout << ans[i] << "\n";
  return 0;
}
