#include <bits/stdc++.h>
using namespace std;
const int N = 4005, M = 20005;
int n, p, m, ans[M];
struct Item {
  int c, h;
};
vector<Item> a[M];
struct Query {
  int v, id;
};
vector<Query> q[M];
int f[N][N], day[N], g[N];
void calc(int pos) {
  int beg = max(1, pos - p), ed = min(20000, pos + p - 1);
  int ptr = 0;
  for (int i = pos - 1; i >= beg; --i)
    for (auto &j : a[i]) {
      day[++ptr] = i;
      for (int k = 1; k <= 4000; k++) {
        f[ptr][k] = max(f[ptr - 1][k], f[ptr][k - 1]);
        if (k >= j.c) f[ptr][k] = max(f[ptr][k], f[ptr - 1][k - j.c] + j.h);
      }
    }
  memset(g, 0, sizeof(g));
  int cur = ptr;
  for (int i = pos; i <= ed; i++) {
    for (auto &j : a[i])
      for (int k = 4000; k >= j.c; --k) g[k] = max(g[k], g[k - j.c] + j.h);
    while (cur && day[cur] <= i - p) --cur;
    for (auto &j : q[i])
      for (int k = 0; k <= j.v; k++)
        ans[j.id] = max(ans[j.id], f[cur][k] + g[j.v - k]);
  }
}
int main() {
  cin >> n >> p;
  int t1, t2, t3;
  for (int i = 1; i <= n; i++) cin >> t1 >> t2 >> t3, a[t3].push_back({t1, t2});
  cin >> m;
  for (int i = 1; i <= m; i++) cin >> t1 >> t2, q[t1].push_back({t2, i});
  for (int i = 1; i <= 20000; i += p) calc(i);
  for (int i = 1; i <= m; i++) cout << ans[i] << endl;
  return 0;
}
