#include <bits/stdc++.h>
using namespace std;
int n, a, b, c, d, k, m, q, z, p, t;
const int MXT = 2e5 + 4;
vector<pair<int, int> > add[MXT];
int rem[MXT];
vector<pair<int, int> > query[MXT];
int ans[MXT];
vector<int> dodaj(vector<int> V, int c, int h) {
  while (V.size() < 8000) V.push_back(0);
  for (int i = V.size() - 1; i >= (0); i--) {
    if (i + c >= V.size()) continue;
    V[i + c] = max(V[i + c], V[i] + h);
  }
  return V;
}
vector<pair<vector<int>, pair<int, int> > > stack1, stack2;
void dodajel(pair<int, int> x) {
  if (stack1.size() == 0) {
    stack1.push_back(make_pair(dodaj(vector<int>(), x.first, x.second), x));
    return;
  }
  stack1.push_back(make_pair(dodaj(stack1.back().first, x.first, x.second), x));
}
void usun() {
  if (stack2.size()) {
    stack2.pop_back();
    return;
  }
  stack2.push_back(make_pair(dodaj(vector<int>(), stack1.back().second.first,
                                   stack1.back().second.second),
                             stack1.back().second));
  stack1.pop_back();
  while (stack1.size()) {
    stack2.push_back(
        make_pair(dodaj(stack2.back().first, stack1.back().second.first,
                        stack1.back().second.second),
                  stack1.back().second));
    stack1.pop_back();
  }
  stack2.pop_back();
}
int lacz(vector<int> V1, vector<int> V2, int k) {
  while (V1.size() < 8000) V1.push_back(0);
  while (V2.size() < 8000) V2.push_back(0);
  int res = 0;
  for (int i = 0; i <= (k); i++) {
    res = max(res, V1[i] + V2[k - i]);
  }
  return res;
}
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= (n); i++) {
    scanf("%d %d %d", &a, &b, &t);
    add[t].push_back(make_pair(a, b));
    rem[t + p]++;
  }
  scanf("%d", &q);
  for (int i = 1; i <= (q); i++) {
    scanf("%d%d", &a, &b);
    query[a].push_back(make_pair(b, i));
  }
  for (int i = 1; i <= (20000); i++) {
    for (int j = 0; j < (add[i].size()); j++) {
      dodajel(add[i][j]);
    }
    for (int j = 0; j < (rem[i]); j++) {
      usun();
    }
    for (int j = 0; j < (query[i].size()); j++) {
      if (stack1.size() == 0 && stack2.size() == 0) continue;
      if (stack1.size() == 0) {
        ans[query[i][j].second] =
            lacz(vector<int>(), stack2.back().first, query[i][j].first);
        continue;
      }
      if (stack2.size() == 0) {
        ans[query[i][j].second] =
            lacz(stack1.back().first, vector<int>(), query[i][j].first);
        continue;
      }
      ans[query[i][j].second] =
          lacz(stack1.back().first, stack2.back().first, query[i][j].first);
    }
    if (i < 10)
      cerr << i << " " << stack1.size() << " " << stack2.size() << endl;
  }
  for (int i = 1; i <= (q); i++) {
    printf("%d\n", ans[i]);
  }
}
