#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:66777216")
using namespace std;
struct S {
  vector<pair<int, int> > t;
  vector<vector<int> > dp;
  inline void push(int cs, int hap) {
    t.push_back(make_pair(cs, hap));
    vector<int> res(4001, 0);
    for (int _n(((int)((res).size())) - 1), i(0); i <= _n; i++) {
      if (!dp.empty()) res[i] = dp.back()[i];
      if (i >= cs) {
        int can = hap;
        if (!dp.empty()) can += dp.back()[i - cs];
        res[i] = max(res[i], can);
      }
      if (i) res[i] = max(res[i], res[i - 1]);
    }
    dp.emplace_back(move(res));
  }
  inline pair<int, int> pop() {
    dp.pop_back();
    pair<int, int> r = t.back();
    t.pop_back();
    return r;
  }
  inline bool empty() { return t.empty(); }
};
int a, b, c, d, n, m, k, p;
pair<int, pair<int, int> > mas[4002];
pair<int, int> quer[20002];
int res[20002];
S q1, q2;
inline void push(int cs, int hap) { q1.push(cs, hap); }
inline void pop() {
  if (!q2.empty()) {
    q2.pop();
  } else {
    while (!q1.empty()) {
      pair<int, int> t = q1.pop();
      q2.push(t.first, t.second);
    }
    q2.pop();
  }
}
inline int fnd(int b) {
  int ans = 0;
  for (int _n((b + 1) - 1), i(0); i <= _n; i++) {
    int c1 = 0, c2 = 0;
    if (!q1.empty()) c1 = max(c1, q1.dp.back()[i]);
    if (!q2.empty()) c2 = max(c2, q2.dp.back()[b - i]);
    ans = max(ans, c1 + c2);
  }
  return ans;
}
int main() {
  scanf("%d%d", &n, &p);
  vector<pair<int, pair<int, int> > > ev;
  for (int _n((n)-1), i(0); i <= _n; i++) {
    scanf("%d%d%d", &a, &b, &c);
    mas[i] = make_pair(c, make_pair(a, b));
    ev.push_back(make_pair(c, make_pair(1, i)));
    ev.push_back(make_pair(c + p, make_pair(0, i)));
  }
  scanf("%d", &m);
  for (int _n((m)-1), i(0); i <= _n; i++) {
    scanf("%d%d", &quer[i].first, &quer[i].second);
    ev.push_back(make_pair(quer[i].first, make_pair(2, i)));
  }
  sort((ev).begin(), (ev).end());
  for (int _n(((int)((ev).size())) - 1), i(0); i <= _n; i++) {
    int v = ev[i].second.second;
    if (ev[i].second.first == 1) {
      push(mas[v].second.first, mas[v].second.second);
    } else if (ev[i].second.first == 0) {
      pop();
    } else {
      int ans = fnd(quer[v].second);
      res[v] = ans;
    }
  }
  for (int _n((m)-1), i(0); i <= _n; i++) {
    printf("%d\n", res[i]);
  }
}
