#include <bits/stdc++.h>
using namespace std;
const int MAXC = 4005;
const int MAXT = 20005;
vector<pair<int, int> > item[MAXT], que[MAXT];
int P, fwd[MAXC][MAXC], rev[MAXC][MAXC], ans[MAXT];
void ins(pair<int, int> it, int dp[][MAXC], int pos) {
  for (int i = 1; i < MAXC; ++i) {
    dp[pos][i] = max(dp[pos - 1][i], dp[pos][i - 1]);
    if (i >= it.first)
      dp[pos][i] = max(dp[pos][i], dp[pos - 1][i - it.first] + it.second);
  }
}
void f(int ct) {
  int x = 0, y = 0;
  for (int i = ct; i > max(0, ct - P); --i)
    for (int j = 0; j < item[i].size(); ++j) ins(item[i][j], rev, ++x);
  for (int i = ct + 1; i < min(MAXT, ct + P); ++i)
    for (int j = 0; j < item[i].size(); ++j) ins(item[i][j], fwd, ++y);
  y = 0;
  for (int i = ct; i < min(MAXT, ct + P); ++i) {
    for (int j = 0; j < que[i].size(); ++j) {
      int pos = que[i][j].second, cap = que[i][j].first;
      for (int k = 0; k <= cap; ++k)
        ans[pos] = max(ans[pos], rev[x][k] + fwd[y][cap - k]);
    }
    if (i + 1 - P >= 0) x -= item[i + 1 - P].size();
    if (i + 1 < MAXT) y += item[i + 1].size();
  }
}
int main() {
  int n;
  scanf("%d %d", &n, &P);
  for (int i = 0; i < n; ++i) {
    int c, h, t;
    scanf("%d %d %d", &c, &h, &t);
    item[t].push_back(pair<int, int>(c, h));
  }
  int q;
  scanf("%d", &q);
  for (int i = 0; i < q; ++i) {
    int a, b;
    scanf("%d %d", &a, &b);
    que[a].push_back(pair<int, int>(b, i));
  }
  for (int t = 1; t <= MAXT; t += P) f(t);
  for (int i = 0; i < q; ++i) printf("%d\n", ans[i]);
  return 0;
}
