#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const long long INF = 4e18;
const int inf = 2e9;
const double eps = 1e-13;
const int N = 4005;
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
int lcm(int a, int b) { return a / gcd(a, b) * b; }
int temp[N];
int lef[N][N];
int rig[N][N];
int c[N], h[N], t[N];
pair<int, pair<int, int> > e[N];
int main(void) {
  int i, j, n, p;
  scanf("%d %d", &n, &p);
  for (i = 0; i < n; ++i) {
    scanf("%d %d %d", &c[i], &h[i], &t[i]);
    e[i] = make_pair(t[i], make_pair(c[i], h[i]));
  }
  sort(e, e + n);
  for (i = 0; i < n; ++i) {
    t[i] = e[i].first;
    c[i] = e[i].second.first;
    h[i] = e[i].second.second;
  }
  int beg = 0;
  while (beg < n) {
    int end = beg;
    while (end + 1 < n && t[end + 1] / p == t[beg] / p) {
      end++;
    }
    memset(temp, 0, sizeof(temp));
    for (i = beg; i <= end; ++i) {
      for (j = N - 1; j >= c[i]; --j) {
        temp[j] = max(temp[j], temp[j - c[i]] + h[i]);
      }
      for (j = 0; j < N; ++j) {
        lef[i][j] = temp[j];
      }
    }
    memset(temp, 0, sizeof(temp));
    for (i = end; i >= beg; --i) {
      for (j = N - 1; j >= c[i]; --j) {
        temp[j] = max(temp[j], temp[j - c[i]] + h[i]);
      }
      for (j = 0; j < N; ++j) {
        rig[i][j] = temp[j];
      }
    }
    beg = end + 1;
  }
  int q;
  scanf("%d", &q);
  while (q--) {
    int time, duit;
    scanf("%d %d", &time, &duit);
    int first = -1, last = -1;
    for (i = 0; i < n; ++i) {
      if (t[i] <= time && time < t[i] + p) {
        if (first == -1) {
          first = i;
        }
        last = i;
      }
    }
    if (first == -1) {
      puts("0");
      continue;
    }
    if (t[first] / p == time / p) {
      printf("%d\n", lef[last][duit]);
      continue;
    }
    if (t[last] / p == time / p - 1) {
      printf("%d\n", rig[first][duit]);
      continue;
    }
    int ans = 0;
    for (i = 0; i <= duit; ++i) {
      ans = max(ans, lef[last][i] + rig[first][duit - i]);
    }
    printf("%d\n", ans);
  }
  return 0;
}
