#include <bits/stdc++.h>
using namespace std;
template <typename U, typename V>
void Min(U &a, const V &b) {
  if (a > b) a = b;
}
template <typename U, typename V>
void Max(U &a, const V &b) {
  if (a < b) a = b;
}
template <typename U, typename V>
void add(U &a, const V &b) {
  a = (a + b) % 998244353;
}
template <typename U>
U gcd(U a, U b) {
  if (a == 0) return b;
  if (b == 0) return a;
  if (a >= b)
    return gcd(a % b, b);
  else
    return gcd(a, b % a);
}
int pow(int a, int b) {
  int ans = 1;
  while (b) {
    if (b & 1) ans = 1LL * ans * a % 998244353;
    a = 1LL * a * a % 998244353;
    b >>= 1;
  }
  return ans;
}
struct node {
  int t, a, b, id;
  bool operator<(const node &a) const {
    return t < a.t || (t == a.t && b < a.b);
  }
} e[500005];
int main() {
  int T, i, j, k, m, n, K;
  scanf("%d", &T);
  while (T--) {
    int first;
    scanf("%d%d%d%d", &n, &m, &K, &first);
    for (int i = 0; i < n; i++) {
      scanf("%d%d%d", &e[i].t, &e[i].a, &e[i].b);
      e[i].id = i;
    }
    sort(e, e + n);
    int t = 0, ok = 1, sum = first;
    e[n].t = m;
    set<pair<int, int> > s;
    long long ans = 0;
    for (int i = 0; i < n + 1; i++) {
      int h = e[i].t - t;
      while (first < h) {
        if (s.empty()) {
          ok = 0;
          break;
        }
        int u = s.begin()->second;
        int z = min(e[u].a, h - first);
        first += z;
        ans += 1LL * e[u].b * z;
        e[u].a -= z;
        if (e[u].a == 0) s.erase(s.begin());
      }
      first -= h;
      sum -= h;
      if (!ok) break;
      if (i == n) break;
      t = e[i].t;
      while (sum + e[i].a > K && !s.empty()) {
        int u = s.rbegin()->second;
        if (e[u].b <= e[i].b) break;
        sum -= e[u].a;
        if (sum + e[i].a <= K) {
          k = K - sum - e[i].a;
          if (k)
            e[u].a = k, sum += e[u].a;
          else
            s.erase(--s.end());
          break;
        }
        s.erase(--s.end());
      }
      k = min(e[i].a, K - sum);
      if (k) s.insert({e[i].b, i}), sum += k, e[i].a = k;
    }
    if (!ok)
      puts("-1");
    else {
      printf("%lld\n", ans);
    }
  }
}
