#include <bits/stdc++.h>
using namespace std;
const int C = 4003;
const int N = 4003;
const int T = 20003;
int cur_cnt = 0;
int dp[N][C];
vector<pair<int, int>> t[4 * T];
vector<int> query_b[T];
vector<int *> query_ans[T];
void add_object(int v, int l, int r, int ql, int qr, pair<int, int> obj) {
  if (qr <= l || r <= ql) {
    return;
  } else if (ql <= l && r <= qr) {
    t[v].push_back(obj);
  } else {
    int m = (r + l) >> 1;
    add_object(2 * v + 1, l, m, ql, qr, obj);
    add_object(2 * v + 2, m, r, ql, qr, obj);
  }
}
void dfs(int v, int l, int r) {
  int was_cnt = cur_cnt;
  for (auto [c, h] : t[v]) {
    fill(dp[cur_cnt + 1], dp[cur_cnt + 1] + C, 0);
    for (int was = 0; was < C; was++) {
      if (was + c < C) {
        dp[cur_cnt + 1][was + c] =
            max(dp[cur_cnt + 1][was + c], dp[cur_cnt][was] + h);
      }
      dp[cur_cnt + 1][was] = max(dp[cur_cnt + 1][was], dp[cur_cnt][was]);
    }
    cur_cnt++;
  }
  if (l + 1 == r) {
    for (int i = 0; i < (int)query_b[l].size(); i++) {
      *query_ans[l][i] =
          (*max_element(dp[cur_cnt], dp[cur_cnt] + query_b[l][i] + 1));
    }
  } else {
    int m = (r + l) >> 1;
    dfs(2 * v + 1, l, m);
    dfs(2 * v + 2, m, r);
  }
  cur_cnt = was_cnt;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int n, p;
  cin >> n >> p;
  for (int i = 0; i < n; i++) {
    int c, h, st;
    cin >> c >> h >> st;
    st--;
    add_object(0, 0, T, st, st + p, {c, h});
  }
  int q;
  cin >> q;
  vector<int> ans(q);
  for (int i = 0; i < q; i++) {
    int a, b;
    cin >> a >> b;
    a--;
    query_b[a].push_back(b);
    query_ans[a].push_back(&ans[i]);
  }
  dfs(0, 0, T);
  for (auto x : ans) {
    cout << x << '\n';
  }
}
