#include <bits/stdc++.h>
using namespace std;
struct ss {
  int c, h;
  ss(int cc, int hh) {
    c = cc;
    h = hh;
  }
};
vector<ss> ax[20010];
vector<ss> rx[20010];
vector<ss> qx[20010];
int fd[4040];
int bk[4040][4040];
int ct[20040];
int ou[20040];
int tt[20040];
int main() {
  int n, p;
  scanf("%d%d", &n, &p);
  for (int i = 0; i < n; i++) {
    int c, h, t;
    scanf("%d%d%d", &c, &h, &t);
    ax[t].push_back(ss(c, h));
    rx[t + p - 1].push_back(ss(c, h));
  }
  int q;
  scanf("%d", &q);
  for (int i = 0; i < q; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    ou[i] = -1;
    qx[a].push_back(ss(i, b));
    tt[i] = a;
  }
  for (int i = 1; (i - 1) * p + 1 <= 20000; i++) {
    int b = (i - 1) * p + 1;
    int e = min(i * p, 20000);
    ct[e] = 0;
    for (int j = e - 1; j >= b; j--) {
      ct[j] = ct[j + 1];
      if (rx[j].size() != 0) {
        ct[j]++;
        for (int k = 0; k <= 4000; k++) bk[ct[j]][k] = bk[ct[j] - 1][k];
        for (int l = 0; l < rx[j].size(); l++) {
          for (int k = 4000; k >= rx[j][l].c; k--) {
            bk[ct[j]][k] =
                max(bk[ct[j]][k], bk[ct[j]][k - rx[j][l].c] + rx[j][l].h);
          }
        }
      }
    }
    for (int j = 0; j <= 4000; j++) fd[j] = 0;
    for (int j = b; j <= e; j++) {
      for (int k = 0; k < ax[j].size(); k++) {
        for (int l = 4000; l >= ax[j][k].c; l--)
          fd[l] = max(fd[l], fd[l - ax[j][k].c] + ax[j][k].h);
      }
      for (int k = 0; k < qx[j].size(); k++) {
        int an = 0;
        int bb = qx[j][k].h;
        for (int i = 0; i <= bb; i++) {
          an = max(an, fd[i] + bk[ct[j]][bb - i]);
        }
        ou[qx[j][k].c] = an;
      }
    }
  }
  for (int i = 0; i < q; i++) printf("%d\n", ou[i]);
}
