#include <bits/stdc++.h>
using namespace std;
const int N = 4005;
inline int read() {
  int x = 0;
  char c = getchar();
  while (c < '0' || c > '9') c = getchar();
  while (c >= '0' && c <= '9')
    x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
  return x;
}
struct node {
  int c, w, t, id;
  inline bool operator<(const node &x) const { return t < x.t; }
} a[N];
int i, j, n, m;
int Li[N][N], Ri[N][N];
inline void Do(int &x, int y) { (x < y) && (x = y); }
void pre() {
  for (i = 1; i <= n; i++) {
    if (i == 1 || a[i].id != a[i - 1].id) {
      for (j = a[i].c; j <= 4000; j++) Li[i][j] = a[i].w;
    } else {
      memcpy(Li[i], Li[i - 1], sizeof(Li[i]));
      for (j = 4000; j >= a[i].c; j--) Do(Li[i][j], Li[i][j - a[i].c] + a[i].w);
    }
  }
  for (i = n; i >= 1; i--) {
    if (i == n || a[i].id != a[i + 1].id) {
      for (j = a[i].c; j <= 4000; j++) Ri[i][j] = a[i].w;
    } else {
      memcpy(Ri[i], Ri[i + 1], sizeof(Ri[i]));
      for (j = 4000; j >= a[i].c; j--) Do(Ri[i][j], Ri[i][j - a[i].c] + a[i].w);
    }
  }
}
int tmp[N];
int main() {
  n = read(), m = read();
  for (i = 1; i <= n; ++i) {
    int c = read(), w = read(), t = read();
    a[i] = (node){c, w, t, t / m};
    tmp[i] = t;
  }
  sort(a + 1, a + n + 1);
  sort(tmp + 1, tmp + n + 1);
  pre();
  int q = read();
  while (q--) {
    int st = read(), b = read(), res = 0;
    int ql = lower_bound(tmp + 1, tmp + n + 1, max(st - m + 1, 1)) - tmp;
    int qr = upper_bound(tmp + 1, tmp + n + 1, st) - tmp - 1;
    if (ql > qr) {
      puts("0");
      continue;
    }
    if (a[ql].id == a[qr].id) {
      if (a[ql].id == st / m)
        res = Li[qr][b];
      else
        res = Ri[ql][b];
    } else
      for (i = 0; i <= b; i++) res = max(res, Li[qr][i] + Ri[ql][b - i]);
    printf("%d\n", res);
  }
}
