#include <bits/stdc++.h>
using namespace std;
const int MAXN = 4010;
const int MAXT = 1 << 15;
int N, P, Q;
vector<pair<int, int> > qu[MAXT];
vector<pair<int, int> > items[2 * MAXT];
int ans[MAXT];
void update(int a, int b, pair<int, int> v, int cur = 1, int lt = 0,
            int rt = MAXT) {
  if (rt <= a || b <= lt) {
    return;
  }
  if (a <= lt && rt <= b) {
    items[cur].push_back(v);
    return;
  }
  int mid = (lt + rt) / 2;
  update(a, b, v, 2 * cur, lt, mid);
  update(a, b, v, 2 * cur + 1, mid, rt);
}
int dp[17][MAXN];
void rec(int lt = 0, int rt = MAXT, int cur = 1, int dep = 0) {
  if (dep) {
    memcpy(dp[dep], dp[dep - 1], sizeof(dp[dep]));
  }
  for (pair<int, int> p : items[cur]) {
    for (int i = MAXN - 1; i >= p.first; i--) {
      dp[dep][i] = max(dp[dep][i], dp[dep][i - p.first] + p.second);
    }
  }
  if (rt == lt + 1) {
    for (pair<int, int> p : qu[lt]) {
      ans[p.second] = dp[dep][p.first];
    }
  } else {
    int mid = (lt + rt) / 2;
    rec(lt, mid, 2 * cur, dep + 1);
    rec(mid, rt, 2 * cur + 1, dep + 1);
  }
}
int main() {
  scanf("%d %d", &N, &P);
  for (int i = 0; i < N; i++) {
    int c, h, t;
    scanf("%d %d %d", &c, &h, &t);
    update(t, t + P, pair<int, int>(c, h));
  }
  scanf("%d", &Q);
  for (int i = 0; i < Q; i++) {
    int t, b;
    scanf("%d %d", &t, &b);
    qu[t].push_back(pair<int, int>(b, i));
  }
  rec();
  for (int i = 0; i < Q; i++) {
    printf("%d\n", ans[i]);
  }
}
