#include <bits/stdc++.h>
using namespace std;
struct Event {
  int l, r, ind;
  Event() : l(), r(), ind() {}
  Event(int _l, int _r, int _ind) : l(_l), r(_r), ind(_ind) {}
};
const int N = 4005;
const int T = 33000;
const int SIZE = (1 << 15);
int n, p, q;
int cost[N], happy[N];
int query_money[T];
int query_res[T];
vector<int> queries[T];
struct Knapsack {
  int dp[N][N];
  int size;
  vector<pair<int *, int>> history;
  vector<int> snapshots;
  Knapsack() : dp(), size() {}
  void change(int *ptr, int val) {
    history.push_back(make_pair(ptr, *ptr));
    *ptr = val;
  }
  void undo() {
    int *ptr = history.back().first;
    int val = history.back().second;
    *ptr = val;
    history.pop_back();
  }
  void snapshot() { snapshots.push_back((int)history.size()); }
  void recover() {
    while ((int)history.size() > snapshots.back()) undo();
    snapshots.pop_back();
  }
  void add(int ind) {
    0;
    change(&size, size + 1);
    for (int i = 0; i < N; i++) {
      int old_sum = i - cost[ind];
      int val = max((old_sum < 0 ? 0 : dp[size - 1][old_sum] + happy[ind]),
                    dp[size - 1][i]);
      change(&dp[size][i], val);
    }
  }
  int get(int money) { return dp[size][money]; }
  void dump() {
    0;
    for (int i = 0; i <= size; i++) {
      for (int j = 0; j < 10; j++) 0;
      0;
    }
  }
};
Knapsack knapsack;
bool intersects(int a, int b, int c, int d) {
  int x = max(a, c);
  int y = min(b, d);
  return x <= y;
}
void solve(int l, int r, vector<Event> &events) {
  knapsack.snapshot();
  for (Event e : events)
    if (e.l <= l && r <= e.r) knapsack.add(e.ind);
  if (l == r) {
    for (int query : queries[l]) {
      query_res[query] = knapsack.get(query_money[query]);
    }
  } else {
    int m = (l + r) / 2;
    vector<Event> left, right;
    for (Event e : events) {
      if (e.l <= l && r <= e.r) continue;
      if (intersects(l, m, e.l, e.r)) left.push_back(e);
      if (intersects(m + 1, r, e.l, e.r)) right.push_back(e);
    }
    solve(l, m, left);
    solve(m + 1, r, right);
  }
  knapsack.recover();
}
void solve() {
  vector<Event> events;
  scanf("%d%d", &n, &p);
  for (int i = 0; i < n; i++) {
    int time;
    scanf("%d%d%d", &cost[i], &happy[i], &time);
    events.push_back(Event(time, time + p - 1, i));
  }
  scanf("%d", &q);
  for (int i = 0; i < q; i++) {
    int time;
    scanf("%d%d", &time, &query_money[i]);
    queries[time].push_back(i);
  }
  solve(0, SIZE - 1, events);
  for (int i = 0; i < q; i++) printf("%d\n", query_res[i]);
}
int main() {
  solve();
  0;
  return 0;
}
