#include <bits/stdc++.h>
using namespace std;
const int N = 4010;
const int T = 20010;
int n, p, q, c[N], h[N], t[N], cs[T], cd[T], b[T], rez[T];
int d[10010][N];
vector<int> v[T], v2[T], v3[T];
void sol(int pozs) {
  int pozd = min(T - 1, pozs + 2 * p), mid = pozs + p;
  vector<int>::iterator it;
  int i, j;
  for (i = pozs; i <= mid; ++i) memset(d[i - pozs], 0, sizeof(d[i - pozs]));
  int din[N];
  memset(din, 0, sizeof(din));
  for (i = mid - 1; i >= pozs; --i) {
    for (it = v[i].begin(); it != v[i].end(); ++it)
      for (j = N - 1; j >= c[*it]; --j)
        din[j] = max(din[j], din[j - c[*it]] + h[*it]);
    memcpy(d[i - pozs], din, sizeof(din));
  }
  memset(din, 0, sizeof(din));
  for (i = mid; i <= pozd; ++i) {
    for (it = v[i].begin(); it != v[i].end(); ++it)
      for (j = N - 1; j >= c[*it]; --j)
        din[j] = max(din[j], din[j - c[*it]] + h[*it]);
    for (it = v2[i - p].begin(); it != v2[i - p].end(); ++it)
      for (j = 0; j <= b[*it]; ++j)
        rez[*it] = max(rez[*it], d[i - p - pozs][j] + din[b[*it] - j]);
  }
}
void sol1() {
  int i, j;
  int din[N];
  memset(din, 0, sizeof(din));
  vector<int>::iterator it;
  for (i = 1; i <= p + 1; ++i) {
    for (it = v[i].begin(); it != v[i].end(); ++it)
      for (j = N - 1; j >= c[*it]; --j)
        din[j] = max(din[j], din[j - c[*it]] + h[*it]);
    for (it = v3[i].begin(); it != v3[i].end(); ++it) rez[*it] = din[b[*it]];
  }
}
int main() {
  int i, j, k;
  cin >> n >> p;
  --p;
  for (i = 1; i <= n; ++i) {
    cin >> c[i] >> h[i] >> t[i];
    v[t[i]].push_back(i);
  }
  cin >> q;
  for (i = 1; i <= q; ++i) {
    cin >> cd[i] >> b[i];
    cs[i] = max(1, cd[i] - p);
    if (cs[i] == 1) {
      v3[cd[i]].push_back(i);
      continue;
    }
    v2[cs[i]].push_back(i);
  }
  sol1();
  for (int t = 0; t + p < T; t += p) sol(t);
  for (i = 1; i <= q; ++i) cout << rez[i] << "\n";
  return 0;
}
