#include <bits/stdc++.h>
using namespace std;
const int N = int(3e5), mod = int(1e9) + 7;
int n, p, q, c[N], h[N], t[N], ans[N], del[N];
stack<pair<int, int> > st[3];
vector<pair<int, int> > add[N], g[N];
int d[2][4010][4010];
int sz[3];
void push(int id, pair<int, int> p) {
  st[id].push(p);
  sz[id]++;
  int l = sz[id];
  for (int i = 0; i <= 4000; i++) {
    d[id][l][i] = 0;
    if (i >= p.first) {
      d[id][l][i] = d[id][l - 1][i - p.first] + p.second;
    }
    d[id][l][i] = max(d[id][l][i], d[id][l - 1][i]);
    if (i > 0) d[id][l][i] = max(d[id][l][i], d[id][l][i - 1]);
  }
}
void pop() {
  if (st[1].empty()) {
    while (!st[0].empty()) {
      push(1, st[0].top());
      st[0].pop();
      sz[0]--;
    }
  }
  st[1].pop();
  sz[1]--;
}
int get(int m) {
  int res = 0;
  for (int i = 0; i <= m; i++) {
    res = max(res, d[0][sz[0]][i] + d[1][sz[1]][m - i]);
  }
  return res;
}
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++) {
    scanf("%d%d%d", &c[i], &h[i], &t[i]);
    add[t[i]].push_back(make_pair(c[i], h[i]));
    del[t[i] + p]++;
  }
  scanf("%d", &q);
  for (int i = 1, a, b; i <= q; i++) {
    scanf("%d%d", &a, &b);
    g[a].push_back(make_pair(b, i));
  }
  for (int i = 1; i <= 20000; i++) {
    for (int j = 0; j < add[i].size(); j++) {
      push(0, add[i][j]);
    }
    while (del[i]) {
      pop();
      del[i]--;
    }
    for (int j = 0; j < g[i].size(); j++) {
      ans[g[i][j].second] = get(g[i][j].first);
    }
  }
  for (int i = 1; i <= q; i++) {
    printf("%d\n", ans[i]);
  }
  return 0;
}
