#include <bits/stdc++.h>
using namespace std;
long long modpow(long long b, long long e, long long mod) {
  long long ans = 1;
  for (; e; b = b * b % mod, e /= 2)
    if (e & 1) ans = ans * b % mod;
  return ans;
}
int n, p;
struct query {
  int id, budget;
};
vector<query> tq[20004];
int ans[20004];
template <class T>
struct dcq {
  vector<vector<T>> st;
  int n;
  vector<int> dp;
  dcq(int n) : st(2 * n, vector<T>()), n(n) {}
  void upd(int x, int y, T q) {
    for (x += n, y += n + 1; x < y; x /= 2, y /= 2) {
      if (x & 1) st[x++].push_back(q);
      if (y & 1) st[--y].push_back(q);
    }
    return;
  }
  void solve(int curr = 1) {
    if (curr == 1) dp = vector<int>(4001);
    vector<int> rb = dp;
    for (auto w : st[curr]) {
      for (int i = 4001 - 1; i >= 0; i--) {
        if (i >= w.first) {
          dp[i] = max(dp[i], dp[i - w.first] + w.second);
        }
      }
    }
    if (curr >= n) {
      for (auto w : tq[curr - n]) {
        ans[w.id] = dp[w.budget];
      }
    } else {
      solve(2 * curr);
      solve(2 * curr + 1);
    }
    dp = rb;
    return;
  }
};
int32_t main() {
  cin >> n >> p;
  dcq<pair<int, int>> knapsack(20004);
  for (int i = 0; i < (n); ++i) {
    int c, h, t;
    cin >> c >> h >> t;
    knapsack.upd(t, t + p - 1, {c, h});
  }
  int q;
  cin >> q;
  for (int i = 0; i < (q); ++i) {
    int a, b;
    cin >> a >> b;
    tq[a].push_back({i, b});
  }
  knapsack.solve(1);
  for (int i = 0; i < (q); ++i) {
    cout << ans[i] << '\n';
  }
}
