#include <bits/stdc++.h>
using namespace std;
const int T = (1 << 15);
const int MAXN = 4005;
int knapsz = 0, dp[MAXN][MAXN], ans[T];
vector<pair<int, int> > seg[2 * T], que[2 * T];
void upd(int root, int lm, int rm, int u, int v, pair<int, int> val) {
  if (u <= lm && rm <= v) {
    seg[root].push_back(val);
    return;
  }
  int m = (lm + rm) / 2;
  if (u <= m) upd(2 * root, lm, m, u, v, val);
  if (m < v) upd(2 * root + 1, m + 1, rm, u, v, val);
}
void dfs(int pos) {
  if (pos >= 2 * T) return;
  for (int i = 0; i < seg[pos].size(); ++i) {
    knapsz++;
    int wt = seg[pos][i].first, val = seg[pos][i].second;
    for (int j = 1; j < MAXN; ++j) {
      dp[knapsz][j] = max(dp[knapsz - 1][j], dp[knapsz][j - 1]);
      if (j >= wt)
        dp[knapsz][j] = max(dp[knapsz][j], dp[knapsz - 1][j - wt] + val);
    }
  }
  for (int i = 0; i < que[pos].size(); ++i)
    ans[que[pos][i].second] = dp[knapsz][que[pos][i].first];
  dfs(2 * pos);
  dfs(2 * pos + 1);
  knapsz -= seg[pos].size();
}
int main() {
  int n, p;
  scanf("%d %d", &n, &p);
  for (int i = 0; i < n; ++i) {
    int c, h, t;
    scanf("%d %d %d", &c, &h, &t);
    upd(1, T, 2 * T - 1, T + t, T + t + p - 1, make_pair(c, h));
  }
  int q;
  scanf("%d", &q);
  for (int i = 0; i < q; ++i) {
    int a, b;
    scanf("%d %d", &a, &b);
    que[T + a].push_back(make_pair(b, i));
  }
  dfs(1);
  for (int i = 0; i < q; ++i) printf("%d\n", ans[i]);
  return 0;
}
