#include <bits/stdc++.h>
long long gi() {
  long long x = 0, f = 1;
  char ch = getchar();
  while (!isdigit(ch)) f ^= ch == '-', ch = getchar();
  while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
  return f ? x : -x;
}
std::mt19937 rnd(time(NULL));
template <class T>
void cxk(T& a, T b) {
  a = a > b ? a : b;
}
template <class T>
void cnk(T& a, T b) {
  a = a < b ? a : b;
}
int pc[4010], ph[4010], pt[4010], u[8010], qa[20010], qb[20010];
std::vector<int> seg[32010], ques[8010];
int ans[20010];
void update(int x, int l, int r, int L, int R, int i) {
  if (L <= l && r <= R) return seg[x].push_back(i);
  if (L <= ((l + r) >> 1)) update(x << 1, l, ((l + r) >> 1), L, R, i);
  if (((l + r) >> 1) < R) update(x << 1 | 1, ((l + r) >> 1) + 1, r, L, R, i);
}
int bag[4010];
void DFS(int x, int l, int r) {
  int _bag[4010];
  memcpy(_bag, bag, sizeof bag);
  for (int i : seg[x])
    for (int j = 4000; j >= pc[i]; --j) cxk(bag[j], bag[j - pc[i]] + ph[i]);
  if (l == r)
    for (int i : ques[l]) ans[i] = bag[qb[i]];
  else
    DFS(x << 1, l, ((l + r) >> 1)), DFS(x << 1 | 1, ((l + r) >> 1) + 1, r);
  memcpy(bag, _bag, sizeof bag);
}
int main() {
  int n = gi(), p = gi();
  for (int i = 1; i <= n; ++i)
    pc[i] = gi(), ph[i] = gi(), pt[i] = gi(), u[++*u] = pt[i],
    u[++*u] = pt[i] + p;
  std::sort(u + 1, u + *u + 1);
  *u = std::unique(u + 1, u + *u + 1) - u - 1;
  for (int i = 1; i <= n; ++i) {
    int l = pt[i], r = pt[i] + p;
    l = std::lower_bound(u + 1, u + *u + 1, l) - u;
    r = std::lower_bound(u + 1, u + *u + 1, r) - u - 1;
    update(1, 1, *u, l, r, i);
  }
  int q = gi();
  for (int i = 1; i <= q; ++i) {
    qa[i] = gi(), qb[i] = gi();
    qa[i] = std::upper_bound(u + 1, u + *u + 1, qa[i]) - u - 1;
    ques[qa[i]].push_back(i);
  }
  DFS(1, 1, *u);
  for (int i = 1; i <= q; ++i) printf("%d\n", ans[i]);
  return 0;
}
