#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
void qread(int &x) {
  int neg = 1;
  x = 0;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') neg = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') x = 10 * x + c - '0', c = getchar();
  x *= neg;
}
const int maxn = 4005;
const int maxm = 10005;
int n, p, q;
int val[maxm][maxn], cur[maxn], ans[maxm * 2];
vector<int> num[maxm * 2];
class Item {
 public:
  int c, h, t;
  bool operator<(const Item &o) const { return t < o.t; }
} a[maxn];
class Query {
 public:
  int t, m, id;
  bool operator<(const Query &o) const { return t < o.t; }
} b[maxm * 2];
void add(int i) {
  for (int j = 4000 - a[i].c; j >= 0; j--)
    cur[j + a[i].c] = max(cur[j + a[i].c], cur[j] + a[i].h);
  for (int(j) = 1; (j) <= 4000; j++) cur[j] = max(cur[j], cur[j - 1]);
}
int main() {
  scanf("%d%d", &n, &p);
  for (int(i) = 0; (i) < n; i++)
    scanf("%d%d%d", &a[i].c, &a[i].h, &a[i].t), a[i].t--;
  sort(a, a + n);
  for (int(i) = 0; (i) < n; i++) num[a[i].t].push_back(i);
  for (int i = 9999; i >= 0; i--) {
    if ((i + 1) % p == 0 || i == 9999) memset(cur, 0, sizeof(cur));
    for (int(j) = 0; (j) < num[i].size(); j++) add(num[i][j]);
    for (int(j) = 0; (j) < 4001; j++) val[i][j] = cur[j];
  }
  memset(cur, 0, sizeof(cur));
  scanf("%d", &q);
  for (int(i) = 0; (i) < q; i++) {
    b[i].id = i;
    scanf("%d%d", &b[i].t, &b[i].m);
    b[i].t--;
  }
  sort(b, b + q);
  int l = 1e9, r = -1e9;
  for (int(i) = 0; (i) < q; i++) {
    int cl = b[i].t - p + 1, cr = b[i].t;
    if (cl >= 10000) {
      l = cl;
      r = cr;
      ans[b[i].id] = 0;
      continue;
    }
    int last = l < 0 ? -1 : l / p, now = cl < 0 ? -1 : cl / p;
    if (last == now) {
      for (int j = r + 1; j <= cr; j++)
        for (int(k) = 0; (k) < num[j].size(); k++) add(num[j][k]);
    } else {
      memset(cur, 0, sizeof(cur));
      for (int j = (cr + 1) / p * p; j <= cr; j++)
        for (int(k) = 0; (k) < num[j].size(); k++) add(num[j][k]);
    }
    l = cl;
    r = cr;
    int res = 0;
    for (int(j) = 0; (j) < b[i].m + 1; j++)
      res = max(res, (l < 0 ? 0 : val[l][j]) + cur[b[i].m - j]);
    ans[b[i].id] = res;
  }
  for (int(i) = 0; (i) < q; i++) printf("%d\n", ans[i]);
  return 0;
}
