#include <bits/stdc++.h>
const int N = 4001, M = 20005;
void up(int &x, int y) { x = std::max(x, y); }
int n, p, q, tail[N][N], head[N], ans[M];
int tail_size = 0;
std::stack<std::pair<int, int>> s;
std::vector<std::pair<int, int>> modify[M], query[M];
void insert(int *a, std::pair<int, int> p) {
  for (int i = N - 1; i >= p.first; --i) up(a[i], a[i - p.first] + p.second);
}
void rebuild() {
  tail_size = s.size();
  for (int i = 1; i <= tail_size; ++i) {
    std::memcpy(tail[i], tail[i - 1], sizeof tail[0]);
    insert(tail[i], s.top()), s.pop();
  }
  std::memset(head, 0, sizeof head);
}
void pop() {
  if (!tail_size) rebuild();
  --tail_size;
}
int ask(int s) {
  int ans = 0;
  for (int i = 0; i <= s; ++i)
    ans = std::max(ans, tail[tail_size][i] + head[s - i]);
  return ans;
}
int main() {
  std::ios::sync_with_stdio(0), std::cin.tie(0);
  std::cin >> n >> p;
  for (int i = 1; i <= n; ++i) {
    int a, h, t;
    std::cin >> a >> h >> t;
    modify[t].emplace_back(a, h);
  }
  std::cin >> q;
  for (int i = 1; i <= q; ++i) {
    int a, t;
    std::cin >> a >> t;
    query[a].emplace_back(i, t);
  }
  for (int i = 1; i <= 20000; ++i) {
    for (auto t : modify[i]) insert(head, t), s.emplace(t);
    if (i >= p)
      for (int j = 0; j < modify[i - p].size(); ++j) pop();
    for (auto t : query[i]) ans[t.first] = ask(t.second);
  }
  for (int i = 1; i <= q; ++i) std::cout << ans[i] << '\n';
  return 0;
}
