#include <bits/stdc++.h>
using namespace std;
const int inf = ~0U >> 1;
const long long INF = ~0ULL >> 1;
template <class T>
inline void read(T &n) {
  char c;
  for (c = getchar(); !(c >= '0' && c <= '9'); c = getchar())
    ;
  n = c - '0';
  for (c = getchar(); c >= '0' && c <= '9'; c = getchar()) n = n * 10 + c - '0';
}
int Pow(int base, int n, int mo) {
  if (n == 0) return 1;
  if (n == 1) return base % mo;
  int tmp = Pow(base, n >> 1, mo);
  tmp = (long long)tmp * tmp % mo;
  if (n & 1) tmp = (long long)tmp * base % mo;
  return tmp;
}
int N, P, Q, dp[4500], ans[30000], cost[5000], hap[5000], ti[5000];
pair<int, int> q[30000];
vector<int> E[30000];
void append(int id) {
  for (int i = (4000 - cost[id]); i >= (0); --i)
    dp[i + cost[id]] = max(dp[i + cost[id]], dp[i] + hap[id]);
}
void solve(int l, int r, vector<pair<pair<int, int>, int> > item) {
  if (l == r) {
    int tmp[4500];
    memcpy(tmp, dp, sizeof(tmp));
    for (int i = (0); i < (item.size()); ++i) append(item[i].second);
    for (auto i : E[l])
      for (int j = (0); j <= (q[i].second); ++j) ans[i] = max(ans[i], dp[j]);
    memcpy(dp, tmp, sizeof(dp));
    return;
  }
  int tmp[4500];
  memcpy(tmp, dp, sizeof(tmp));
  vector<pair<pair<int, int>, int> > L, R;
  L.clear(), R.clear();
  int m = l + r >> 1;
  for (int i = (0); i < (item.size()); ++i) {
    if (item[i].first.first == l && item[i].first.second == r)
      append(item[i].second);
    else if (item[i].first.second <= m)
      L.push_back(item[i]);
    else if (item[i].first.first > m)
      R.push_back(item[i]);
    else
      L.push_back(
          (make_pair((make_pair(item[i].first.first, m)), item[i].second))),
          R.push_back((make_pair((make_pair(m + 1, item[i].first.second)),
                                 item[i].second)));
  }
  solve(l, m, L);
  solve(m + 1, r, R);
  memcpy(dp, tmp, sizeof(dp));
}
int main() {
  scanf("%d%d", &N, &P);
  for (int i = (1); i <= (N); ++i) scanf("%d%d%d", &cost[i], &hap[i], &ti[i]);
  scanf("%d", &Q);
  for (int i = (1); i <= (Q); ++i)
    scanf("%d%d", &q[i].first, &q[i].second), E[q[i].first].push_back(i);
  vector<pair<pair<int, int>, int> > t;
  for (int i = (1); i <= (N); ++i)
    t.push_back((make_pair((make_pair(ti[i], ti[i] + P - 1)), i)));
  solve(1, 20000, t);
  for (int i = (1); i <= (Q); ++i) printf("%d\n", ans[i]);
  return 0;
}
