#include <bits/stdc++.h>
using namespace std;
const int maxn = 4000, maxx = 20000;
struct node {
  int f[4000 + 10];
} d[4000 * 2 + 10];
int n, p, q, cnt;
vector<pair<int, int> > vec[20000 + 10];
int r[20000 + 10], l[20000 + 10];
void operator+=(node &a, pair<int, int> x) {
  for (int i = maxn; i >= x.first; i--)
    a.f[i] = max(a.f[i], a.f[i - x.first] + x.second);
}
int main() {
  scanf("%d%d", &n, &p);
  for (int i = 1; i <= n; i++) {
    int x, y, z;
    scanf("%d%d%d", &x, &y, &z);
    vec[z].push_back(make_pair(x, y));
  }
  for (int i = 1; i <= maxx; i += p) {
    for (int j = 0; j < p && i + j <= maxx; ++j) {
      if (j) r[i + j] = r[i + j - 1];
      if (vec[i + j].size()) {
        d[++cnt] = d[r[i + j]];
        r[i + j] = cnt;
        for (int k = 0; k < vec[i + j].size(); ++k) d[cnt] += vec[i + j][k];
      }
    }
    for (int j = 1; j < p && i - j; ++j) {
      if (j > 1) l[i - j] = l[i - j + 1];
      if (vec[i - j].size()) {
        d[++cnt] = d[l[i - j]];
        l[i - j] = cnt;
        for (int k = 0; k < vec[i - j].size(); ++k) d[cnt] += vec[i - j][k];
      }
    }
  }
  scanf("%d", &q);
  for (int i = 1; i <= q; i++) {
    int x, y;
    scanf("%d%d", &x, &y);
    int ans = 0;
    for (int k = 0; k <= y; k++)
      ans =
          max(ans, d[x - p + 1 > 0 ? l[x - p + 1] : 0].f[k] + d[r[x]].f[y - k]);
    printf("%d\n", ans);
  }
  return 0;
}
