#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int sum = 0, f = 1;
  char c = getchar();
  while (c > '9' || c < '0') {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (c <= '9' && c >= '0') {
    sum = sum * 10 + c - '0';
    c = getchar();
  }
  return f * sum;
}
const int N = 20005;
const int M = 4005;
struct tree {
  int l, r;
} t[N << 2];
struct gift {
  int v, w;
} a[N];
struct ques {
  int id, a, b;
} q[N];
int n, p, Q, f[M], pos, ans[N];
vector<int> v[N << 2];
inline bool cmp(ques a, ques b) { return a.a < b.a; }
inline void build(int p, int l, int r) {
  t[p].l = l;
  t[p].r = r;
  if (l == r) return;
  int mid = (l + r) >> 1;
  build(p << 1, l, mid);
  build(p << 1 | 1, mid + 1, r);
}
inline void insert(int p, int l, int r, int x) {
  if (t[p].l >= l && t[p].r <= r) {
    v[p].push_back(x);
    return;
  }
  int mid = (t[p].l + t[p].r) >> 1;
  if (l <= mid) insert(p << 1, l, r, x);
  if (r > mid) insert(p << 1 | 1, l, r, x);
}
inline void dfs(int p) {
  int g[M] = {0};
  memcpy(g, f, sizeof(g));
  for (int i = 0, mx = v[p].size(); i < mx; i++) {
    int x = v[p][i];
    for (int j = M - 1; j >= a[x].w; j--)
      f[j] = max(f[j], f[j - a[x].w] + a[x].v);
  }
  if (t[p].l == t[p].r) {
    while (pos <= Q && q[pos].a < t[p].l) pos++;
    while (pos <= Q && q[pos].a == t[p].l) {
      ans[q[pos].id] = f[q[pos].b];
      pos++;
    }
  } else {
    dfs(p << 1);
    dfs(p << 1 | 1);
  }
  memcpy(f, g, sizeof(f));
}
signed main() {
  n = read();
  p = read();
  build(1, 1, 20000);
  for (int i = 1; i <= n; i++) {
    a[i].w = read();
    a[i].v = read();
    int x = read();
    insert(1, x, x + p - 1, i);
  }
  Q = read();
  for (int i = 1; i <= Q; i++) q[i].a = read(), q[i].b = read();
  for (int i = 1; i <= Q; i++) q[i].id = i;
  sort(q + 1, q + Q + 1, cmp);
  dfs(1);
  for (int i = 1; i <= Q; i++) printf("%d\n", ans[i]);
  return 0;
}
