/*
记忆递归的程序
*/
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define MAX_N 1000
#define INFINITE 1000000
int t, n, x, y, maxHeight;
struct Platform
{
int Lx, Rx, h;
bool operator<(const Platform &p2) const
{
return h > p2.h;
}
};
Platform platForms[MAX_N + 10];
int leftMinTime[MAX_N + 10];
int rightMinTime[MAX_N + 10];
int L[MAX_N + 10];
int MinTime(int I, bool bLeft)
{
int y = platForms[I].h;
int x;
if (bLeft)
x = platForms[I].Lx;
else
x = platForms[I].Rx;
int i;
for (i = I + 1; i <= n; i++)
{
// make sure the downstairs is effective
if (platForms[i].Lx <= x && platForms[i].Rx >= x)
break;
}
if (i <= n)
{
if (y - platForms[i].h > maxHeight)
return INFINITE;
}
else// why else is here?
{
if (y > maxHeight)
return INFINITE;
else
return y;
}
int nLeftTime = y - platForms[i].h + x - platForms[i].Lx;
int nRightTime = y - platForms[i].h + platForms[i].Rx -x;
if (leftMinTime[i] == -1)
leftMinTime[i] = MinTime(i, true);
if (L[i] == -1)
{
L[i] = MinTime(i, false);
}
nLeftTime += leftMinTime[i];
nRightTime += L[i];
if (nLeftTime < nRightTime)
return nLeftTime;
return nRightTime;
}
int main()
{
scanf_s("%d", &t);
for (int i = 0; i < t; i++)
{
memset(leftMinTime, -1, sizeof(leftMinTime));
memset(L, -1, sizeof(rightMinTime));
scanf_s("%d%d%d%d", &n, &x, &y, &maxHeight);
platForms[0].Lx = x;
platForms[0].Rx = x;
platForms[0].h = y;
for (int j = 1; j <= n; j++)
scanf_s("%d%d%d", &platForms[j].Lx, &platForms[j].Rx, &platForms[j].h);
sort(platForms, platForms + n + 1);
printf("%d\n", MinTime(0, true));
}
return 0;
}