#include <bits/stdc++.h>
using namespace std;
const int MAXN = (1 << 18);
const int MAXL = 20042;
const int MAXB = 4042;
struct query {
  int cap, idx;
  query() {
    cap = 0;
    idx = 0;
  }
  query(int _cap, int _idx) {
    cap = _cap;
    idx = _idx;
  }
};
struct event {
  int cost, val;
  event() {
    cost = 0;
    val = 0;
  }
  event(int _cost, int _val) {
    cost = _cost;
    val = _val;
  }
};
struct knapsack {
  int sz;
  int dp[MAXB][MAXB];
  void clear() {
    sz = 0;
    memset(dp, 0, sizeof(dp));
  }
  knapsack() { clear(); }
  void add(event e) {
    sz++;
    dp[sz][0] = 0;
    for (int i = 1; i < MAXB; i++)
      dp[sz][i] = max(dp[sz][i - 1],
                      max(dp[sz - 1][i],
                          (i >= e.cost) ? dp[sz - 1][i - e.cost] + e.val : 0));
  }
};
vector<query> qu[MAXN];
int ans[MAXN];
struct segment_tree {
  vector<event> tr[4 * MAXN];
  void init(int l, int r, int idx) {
    if (l == r) {
      tr[idx].clear();
      return;
    }
    int mid = (l + r) >> 1;
    init(l, mid, 2 * idx + 1);
    init(mid + 1, r, 2 * idx + 2);
    tr[idx].clear();
  }
  void update(int qL, int qR, event val, int l, int r, int idx) {
    if (l > qR || r < qL) return;
    if (qL <= l && r <= qR) {
      tr[idx].push_back(val);
      return;
    }
    int mid = (l + r) >> 1;
    update(qL, qR, val, l, mid, 2 * idx + 1);
    update(qL, qR, val, mid + 1, r, 2 * idx + 2);
  }
  knapsack kp;
  void solve(int l, int r, int idx) {
    for (event e : tr[idx]) kp.add(e);
    if (l == r) {
      for (auto q : qu[l]) ans[q.idx] = kp.dp[kp.sz][q.cap];
      kp.sz -= tr[idx].size();
      return;
    }
    int mid = (l + r) >> 1;
    solve(l, mid, 2 * idx + 1);
    solve(mid + 1, r, 2 * idx + 2);
    kp.sz -= tr[idx].size();
  }
  segment_tree() { kp.clear(); }
};
int n, m, p;
int c[MAXN], h[MAXN], tim[MAXN];
void read() {
  cin >> n >> p;
  for (int i = 0; i < n; i++) cin >> c[i] >> h[i] >> tim[i];
}
segment_tree t;
void solve() {
  t.init(1, MAXL, 0);
  for (int i = 0; i < n; i++)
    t.update(tim[i], tim[i] + p - 1, event(c[i], h[i]), 1, MAXL, 0);
  int q;
  cin >> q;
  for (int i = 0; i < q; i++) {
    int ct, cc;
    cin >> ct >> cc;
    qu[ct].push_back(query(cc, i));
  }
  t.solve(1, MAXL, 0);
  for (int i = 0; i < q; i++) cout << ans[i] << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  read();
  solve();
  return 0;
}
