#include <bits/stdc++.h>
const int M = 20000 + 5;
const int N = 4000 + 5;
int n, p;
struct Item {
  int c, h, t;
  Item() {}
  Item(int _c, int _h, int _t) : c(_c), h(_h), t(_t) {}
  bool operator<(const Item &rhs) const { return t < rhs.t; }
};
std::vector<Item> items[M];
std::vector<int *> prefix[M], suffix[M];
int pool[N + N][N], tot = 1;
inline void toMax(int &a, int b) {
  if (a < b) a = b;
}
void prepare() {
  for (int i = 0; i < M; ++i) {
    if (items[i].empty()) continue;
    std::sort(items[i].begin(), items[i].end());
    {
      int *cur = pool[0];
      for (Item item : items[i]) {
        int *nex = pool[tot++];
        for (int j = N - 1; j >= 0; --j) {
          if (j + item.c < N) toMax(nex[j + item.c], cur[j] + item.h);
          toMax(nex[j], cur[j]);
        }
        prefix[i].push_back(nex);
        cur = nex;
      }
    }
    {
      int *cur = pool[0];
      for (int k = (int)items[i].size() - 1; k >= 0; --k) {
        Item &item = items[i][k];
        int *nex = pool[tot++];
        for (int j = N - 1; j >= 0; --j) {
          if (j + item.c < N) toMax(nex[j + item.c], cur[j] + item.h);
          toMax(nex[j], cur[j]);
        }
        suffix[i].push_back(nex);
        cur = nex;
      }
      std::reverse(suffix[i].begin(), suffix[i].end());
    }
  }
}
int solve(int a, int b) {
  int *left = pool[0], *right = pool[0];
  {
    int id = a / p;
    int l = 0, r = (int)items[id].size() - 1;
    while (l <= r) {
      int mid = l + r >> 1;
      if (items[id][mid].t <= a)
        l = mid + 1;
      else
        r = mid - 1;
    }
    int pos = l - 1;
    if (pos != -1) right = prefix[id][pos];
  }
  {
    int id = a / p - 1;
    if (id != -1) {
      int l = 0, r = (int)items[id].size() - 1;
      while (l <= r) {
        int mid = l + r >> 1;
        if (items[id][mid].t < a - p + 1)
          l = mid + 1;
        else
          r = mid - 1;
      }
      int pos = r + 1;
      if (pos < (int)items[id].size()) left = suffix[id][pos];
    }
  }
  int ret = 0;
  for (int i = 0; i <= b; ++i) {
    toMax(ret, left[i] + right[b - i]);
  }
  return ret;
}
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 0; i < n; ++i) {
    int c, h, t;
    scanf("%d%d%d", &c, &h, &t);
    t--;
    items[t / p].push_back(Item(c, h, t));
  }
  prepare();
  int nq;
  scanf("%d", &nq);
  while (nq--) {
    int a, b;
    scanf("%d%d", &a, &b);
    a--;
    printf("%d\n", solve(a, b));
  }
  return 0;
}
