#include <bits/stdc++.h>
using namespace std;
const int maxN = 4000 + 2;
const int maxM = 10000 + 2;
int N, P, Q, MX;
vector<pair<int, int> > items;
vector<int> stk[maxM << 1];
vector<pair<int, int> > req[maxM << 1];
int res[maxM << 1];
int dp[2][maxN][maxN];
int los[maxN], nlos;
void gao(int T) {
  int low = max(1, T - P + 1), high = min(MX, T + P - 1);
  int i, j, k;
  for (i = 0; i < maxN; i++) {
    dp[0][0][i] = dp[1][0][i] = 0;
    dp[0][i][0] = dp[1][i][0] = 0;
  }
  nlos = 0;
  for (i = T - 1; i >= low; i--) {
    for (k = 0; k < (int)stk[i].size(); k++) {
      los[++nlos] = i;
      for (j = 1; j <= 4000; j++) {
        dp[0][nlos][j] = max(dp[0][nlos][j - 1], dp[0][nlos - 1][j]);
        if (j >= items[stk[i][k]].first)
          dp[0][nlos][j] =
              max(dp[0][nlos][j], dp[0][nlos - 1][j - items[stk[i][k]].first] +
                                      items[stk[i][k]].second);
      }
    }
  }
  int pos = nlos, np = 0;
  for (i = T; i <= high; i++) {
    for (k = 0; k < (int)stk[i].size(); k++) {
      ++np;
      for (j = 1; j <= 4000; j++) {
        dp[1][np][j] = max(dp[1][np][j - 1], dp[1][np - 1][j]);
        if (j >= items[stk[i][k]].first)
          dp[1][np][j] =
              max(dp[1][np][j], dp[1][np - 1][j - items[stk[i][k]].first] +
                                    items[stk[i][k]].second);
      }
    }
    while (pos > 0 && !(los[pos] + P - 1 >= i)) pos--;
    for (k = 0; k < (int)req[i].size(); k++) {
      int cst = req[i][k].first;
      int idx = req[i][k].second;
      for (j = 0; j <= cst; j++)
        res[idx] = max(res[idx], dp[0][pos][j] + dp[1][np][cst - j]);
    }
  }
}
int main() {
  scanf("%d %d", &N, &P);
  int c, h, t;
  for (int i = 0; i < N; i++) {
    scanf("%d %d %d", &c, &h, &t);
    items.push_back(make_pair(c, h));
    stk[t].push_back(i);
  }
  scanf("%d", &Q);
  int a, b;
  MX = 0;
  for (int i = 0; i < Q; i++) {
    scanf("%d %d", &a, &b);
    if (MX < a) MX = a;
    req[a].push_back(make_pair(b, i));
  }
  memset(res, 0, sizeof(res));
  for (int i = 1; i <= MX; i += P) gao(i);
  for (int i = 0; i < Q; i++) printf("%d\n", res[i]);
  return 0;
}
