#include <bits/stdc++.h>
using namespace std;
struct goods {
  int cost, happy, tmd, at;
  goods(int tmd = 0) : tmd(tmd) {}
  bool operator<(goods b) const { return tmd < b.tmd; }
} p[4005];
int N, P, Q, M, ans;
int pre[4005][4005], suf[4005][4005];
int main() {
  int i, j, t, tmp;
  int l, r, last, next;
  scanf("%d %d", &N, &P);
  for (i = 1; i <= N; i++) {
    scanf("%d %d %d", &p[i].cost, &p[i].happy, &p[i].tmd);
    M = max(M, p[i].tmd);
    p[i].at = p[i].tmd / P;
  }
  sort(p + 1, p + 1 + N);
  for (t = 0, l = 1; t * P <= M; t++) {
    for (r = l; r <= N && p[r].at == t; r++)
      ;
    if (r == l) continue;
    for (i = l, last = 0; i < r; last = i, i++)
      for (j = 0; j <= 4000; j++)
        pre[i][j] =
            max(j >= p[i].cost ? pre[last][j - p[i].cost] + p[i].happy : 0,
                pre[last][j]);
    for (i = r - 1, last = 0; i >= l; last = i, i--)
      for (j = 0; j <= 4000; j++)
        suf[i][j] =
            max(j >= p[i].cost ? suf[last][j - p[i].cost] + p[i].happy : 0,
                suf[last][j]);
    l = r;
  }
  scanf("%d", &Q);
  for (i = 1; i <= Q; i++) {
    scanf("%d %d", &t, &tmp);
    l = lower_bound(p + 1, p + 1 + N, goods(t - P + 1)) - p;
    r = upper_bound(p + 1, p + 1 + N, goods(t)) - p - 1;
    ans = 0;
    if (l > r)
      ans = 0;
    else {
      if (p[l].at != p[r].at)
        for (j = 0; j <= tmp; j++) ans = max(ans, pre[r][j] + suf[l][tmp - j]);
      else if (p[l].at == t / P)
        ans = pre[r][tmp];
      else
        ans = suf[l][tmp];
    }
    printf("%d\n", ans);
  }
  return 0;
}
