#include <bits/stdc++.h>
using namespace std;
int n, P, q;
int dp[20][4010];
int s[4010];
int c[4010], h[4010], t[4010];
vector<pair<int, int> > qs[20010];
int ans[20010];
void cdq(int l, int r, int d, vector<int> p) {
  for (int i = 1; i <= 4000; i++) dp[d][i] = dp[d - 1][i];
  for (int i = 0; i < (int)p.size(); i++) {
    if (t[p[i]] <= l && t[p[i]] + P - 1 >= r) {
      for (int j = 4000; j >= c[p[i]]; j--)
        dp[d][j] = max(dp[d][j], dp[d][j - c[p[i]]] + h[p[i]]);
    }
  }
  if (l == r) {
    for (int i = 0; i < (int)qs[l].size(); i++)
      ans[qs[l][i].second] = dp[d][qs[l][i].first];
    return;
  }
  int mid = (l + r) >> 1;
  vector<int> L, R;
  for (int i = 0; i < (int)p.size(); i++) {
    if (t[p[i]] <= l && t[p[i]] + P - 1 >= r) continue;
    if (t[p[i]] <= mid) L.push_back(p[i]);
    if (t[p[i]] + P - 1 > mid) R.push_back(p[i]);
  }
  cdq(l, mid, d + 1, L);
  cdq(mid + 1, r, d + 1, R);
}
int main() {
  scanf("%d%d", &n, &P);
  for (int i = 1; i <= n; i++) scanf("%d%d%d", c + i, h + i, t + i);
  scanf("%d", &q);
  for (int i = 1; i <= q; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    qs[a].push_back(make_pair(b, i));
  }
  vector<int> p;
  for (int i = 1; i <= n; i++) p.push_back(i);
  cdq(1, 20000, 1, p);
  for (int i = 1; i <= q; i++) printf("%d\n", ans[i]);
  return 0;
}
