#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_N 20001
typedef struct
{
int begin, end, w;
} Program;
Program program[MAX_N];
int myHeapLength, n;
int cmpV1(Program *a, Program *b)
{
return a->begin - b->begin;
}
Program myHeap[MAX_N];
void heapPush(Program e)
{
int i = myHeapLength, p;
Program t;
myHeap[myHeapLength++] = e;
while(i)
{
p = (i - 1) / 2;
if(myHeap[i].end < myHeap[p].end)
{
t = myHeap[i];
myHeap[i] = myHeap[p];
myHeap[p] = t;
i = p;
}
else
break;
}
}
Program heapPop()
{
int minChild, i = 0;
Program e = myHeap[0], t;
myHeap[0] = myHeap[--myHeapLength];
while((minChild = 2 * i + 1) < myHeapLength)
{
if(minChild + 1 < myHeapLength && myHeap[minChild + 1].end < myHeap[minChild].end)
++minChild;
if(myHeap[i].end > myHeap[minChild].end)
{
t = myHeap[i];
myHeap[i] = myHeap[minChild];
myHeap[minChild] = t;
i = minChild;
}
else
break;
}
return e;
}
int check(int x)
{
int i = 0, curTime = 0, time;
Program e;
myHeapLength = 0;
while(1)
{
if(myHeapLength == 0 && i == n)
return 1;
if(myHeapLength == 0 && i < n)
{
e = program[i++];
if(e.end <= curTime)
return 0;
if(e.begin > curTime)
curTime = e.begin;
heapPush(e);
}
else
{
++curTime;
while(i < n && program[i].begin < curTime)
heapPush(program[i++]);
time = x;
while(time)
{
if(myHeapLength)
{
e = heapPop();
if(e.end < curTime)
return 0;
if(e.w > time)
{
e.w -= time;
time = 0;
heapPush(e);
}
else
{
time -= e.w;
}
}
else
break;
}
}
if(curTime > 20000)
return 0;
}
}
int main()
{
freopen("d:/input.txt", "r", stdin);
int T, i, min, max, m;
Program t;
scanf("%d", &T);
while(T--)
{
scanf("%d", &n);
for(i = 0; i < n; ++i)
{
scanf("%d%d%d", &program[i].begin, &program[i].end, &program[i].w);
}
qsort(program, n, sizeof(Program), cmpV1);
min = 1;
max = INT_MAX;
while(min < max)
{
m = min + (max - min) / 2;
if(check(m))
max = m;
else
min = m + 1;
}
printf("%d\n", max);
}
return 0;
}