#include <bits/stdc++.h>
using namespace std;
vector<int> thing[20005 * 4], query[20005 * 4];
struct Thing {
  int cost, happy;
} d[20005];
int cost[20005], f[4005], tree[20005 * 4], tmp[16][4005], ans[20005];
int x, i, n, m, p, y;
void build1(int k, int l, int r) {
  if (x <= l && r <= y) {
    thing[k].push_back(i);
    return;
  }
  int mid = (l + r) >> 1;
  if (x <= mid) build1(k << 1, l, mid);
  if (y > mid) build1(k << 1 | 1, mid + 1, r);
}
void build2(int k, int l, int r) {
  tree[k] = 1;
  int mid = (l + r) >> 1;
  if (l == r) {
    query[k].push_back(i);
    return;
  }
  if (x <= mid)
    build2(k << 1, l, mid);
  else
    build2(k << 1 | 1, mid + 1, r);
}
void work(int k, int l, int r, int dep) {
  if (thing[k].size()) {
    memcpy(tmp[dep], f, sizeof(f));
    for (int i = 0; i < thing[k].size(); i++) {
      int lose = d[thing[k][i]].cost, win = d[thing[k][i]].happy;
      for (int j = 4000; j >= lose; j--) f[j] = max(f[j], f[j - lose] + win);
    }
  }
  if (l == r) {
    for (int i = 0; i < query[k].size(); i++)
      ans[query[k][i]] = f[cost[query[k][i]]];
    if (thing[k].size()) memcpy(f, tmp[dep], sizeof(tmp[dep]));
    return;
  }
  int mid = (l + r) >> 1;
  work(k << 1, l, mid, dep + 1);
  work(k << 1 | 1, mid + 1, r, dep + 1);
  if (thing[k].size()) memcpy(f, tmp[dep], sizeof(tmp[dep]));
}
int main() {
  scanf("%d %d", &n, &p);
  for (i = 1; i <= n; i++) {
    scanf("%d%d%d", &d[i].cost, &d[i].happy, &x);
    y = x + p - 1;
    build1(1, 1, 20000);
  }
  scanf("%d", &m);
  for (i = 1; i <= m; i++) {
    scanf("%d%d", &x, &cost[i]);
    build2(1, 1, 20000);
  }
  work(1, 1, 20000, 0);
  for (i = 1; i <= m; i++) printf("%d\n", ans[i]);
}
