#include <bits/stdc++.h>
using namespace std;
int c[4010], h[4010], t[4010];
int a[20010], b[20010];
struct NN {
  int st, ed;
  int ind, t, m;
} nn[20010];
int cmp(NN a, NN b) { return a.t < b.t; }
int ans[21000];
void gao(int *arr, int *out, int cost, int hap) {
  int i;
  memcpy(out, arr, sizeof(int) * 4010);
  for (i = 4000 - cost; i >= 0; i--)
    out[i + cost] = max(out[i + cost], arr[i] + hap);
  for (i = 4000; i; i--) out[i] = max(out[i], out[i - 1]);
}
struct MM {
  int c, h, t;
} mm[21000];
int cmp1(MM a, MM b) { return a.t < b.t; }
vector<NN> vec[20010];
int cnt, lft_st[2005][4010], rht_st[2005][4010];
void dfs(int lft, int rht, int indx) {
  int mid = (lft + rht) / 2;
  if (vec[indx].size() == 0) return;
  if (lft == rht) {
    for (int i = 0; i < vec[indx].size(); i++) {
      NN tmp = vec[indx][i];
      if (tmp.m >= c[lft])
        ans[tmp.ind] = h[lft];
      else
        ans[tmp.ind] = 0;
    }
    return;
  }
  memset(lft_st[0], 0, sizeof(lft_st[0]));
  memset(rht_st[0], 0, sizeof(rht_st[0]));
  for (int i = 1; i <= mid - lft + 1; i++)
    gao(lft_st[i - 1], lft_st[i], c[mid - i + 1], h[mid - i + 1]);
  for (int i = 1; i <= rht - mid; i++)
    gao(rht_st[i - 1], rht_st[i], c[mid + i], h[mid + i]);
  for (int i = 0; i < vec[indx].size(); i++) {
    NN tmp = vec[indx][i];
    if (tmp.st <= mid && tmp.ed > mid) {
      int *ll = lft_st[mid - tmp.st + 1];
      int *rr = rht_st[tmp.ed - mid];
      int bst = 0;
      for (int j = 0; j <= tmp.m; j++) bst = max(bst, ll[j] + rr[tmp.m - j]);
      ans[tmp.ind] = bst;
    } else if (tmp.ed <= mid)
      vec[indx << 1].push_back(tmp);
    else
      vec[(indx << 1) + 1].push_back(tmp);
  }
  dfs(lft, mid, indx << 1);
  dfs(mid + 1, rht, (indx << 1) + 1);
}
int main() {
  int n, p, i, j, k;
  cin >> n >> p;
  for (i = 1; i <= n; i++) cin >> mm[i].c >> mm[i].h >> mm[i].t;
  sort(mm + 1, mm + 1 + n, cmp1);
  for (i = 1; i <= n; i++) c[i] = mm[i].c, h[i] = mm[i].h, t[i] = mm[i].t;
  int q;
  cin >> q;
  for (i = 1; i <= q; i++) {
    cin >> a[i] >> b[i];
    nn[i].ind = i;
    nn[i].t = a[i], nn[i].m = b[i];
  }
  sort(nn + 1, nn + 1 + q, cmp);
  int tmp = 0;
  for (i = 1; i <= q; i++) {
    nn[i].st = n + 1, nn[i].ed = 0;
    int *tt = t + 1;
    int beg = nn[i].t - p + 1;
    int end = nn[i].t;
    for (j = 1; j <= n; j++, tt++)
      if ((*tt) >= beg) {
        nn[i].st = j;
        break;
      }
    for (j = n, tt = t + n; j >= 1; j--, tt--)
      if ((*tt) <= end) {
        nn[i].ed = j;
        break;
      }
    if (nn[i].st <= nn[i].ed && nn[i].st >= 1 && nn[i].ed <= q)
      vec[1].push_back(nn[i]);
  }
  dfs(1, n, 1);
  for (i = 1; i <= q; i++) cout << ans[i] << endl;
}
