#include <bits/stdc++.h>
using namespace std;
const int W = 4000;
int n, p, m, i, j, a[30005], b[30005], h[30005], c[30005], t[30005], ans[30005];
vector<int> q[3][30005];
struct backpack {
  vector<int> rb, re, v;
  vector<vector<int> > cp;
  backpack() {
    rb.resize(W + 5);
    re.resize(W + 5);
    fill(rb.begin(), rb.end(), -1000000005);
    fill(re.begin(), re.end(), -1000000005);
    rb[0] = re[0] = 0;
  }
  void add(int id) {
    for (int i = W - c[id]; i >= 0; i--) {
      if (rb[i] != -1000000005)
        rb[i + c[id]] = max(rb[i + c[id]], rb[i] + h[id]);
    }
    v.push_back(id);
  }
  void del() {
    int i, j, id;
    if (cp.empty()) {
      for (i = (int)v.size() - 1; i >= 0; i--) {
        id = v[i];
        cp.push_back(re);
        for (j = W - c[id]; j >= 0; j--) {
          if (re[j] != -1000000005)
            re[j + c[id]] = max(re[j + c[id]], re[j] + h[id]);
        }
      }
      v.clear();
      fill(rb.begin(), rb.end(), -1000000005);
      rb[0] = 0;
    }
    re = cp.back();
    cp.pop_back();
  }
  int get(int x) {
    int i, j, mx = -1000000005, ans = max(rb[x], re[x]);
    vector<pair<int, int> > res;
    for (i = 0; i <= W; i++) {
      if (re[i] > mx) res.push_back({i, re[i]}), mx = re[i];
    }
    mx = -1000000005;
    j = (int)res.size() - 1;
    for (i = 0; i <= W; i++) {
      if (rb[i] > mx) {
        while (j >= 0 && res[j].first + i > x) j--;
        if (j != -1 && res[j].first + i <= x)
          ans = max(ans, res[j].second + rb[i]);
        mx = rb[i];
      }
    }
    return ans;
  }
} st;
int main() {
  cin >> n >> p;
  for (i = 0; i < n; i++) {
    cin >> c[i] >> h[i] >> t[i];
    q[0][t[i]].push_back(i);
    q[1][t[i] + p].push_back(i);
  }
  cin >> m;
  for (i = 0; i < m; i++) {
    cin >> a[i] >> b[i];
    q[2][a[i]].push_back(i);
  }
  for (i = 0; i <= 30000; i++) {
    for (j = 0; j < q[0][i].size(); j++) st.add(q[0][i][j]);
    for (j = 0; j < q[1][i].size(); j++) st.del();
    for (j = 0; j < q[2][i].size(); j++)
      ans[q[2][i][j]] = st.get(b[q[2][i][j]]);
  }
  for (i = 0; i < m; i++) cout << ans[i] << endl;
  return 0;
}
