#include <stdio.h>

#define NMAX 333
#define INF 666666666

#define min(a,b) ((a) <= (b) ? (a) : (b))
#define max(a,b) ((a) >= (b) ? (a) : (b))

int Tmin[NMAX][NMAX];
int res[2][NMAX], t[2][NMAX];
int i, j, k, a, b, N, C, T, Ta, Tb;

void bkt(int a, int b)
{
	int Tprev;

	if (a > N && b > N)
	{
		C = min(C, max(Ta, Tb));
		fprintf(stderr, "C=%d\n", C);
	}
	else
	if (a > N)
	{
		Tb += t[1][b];
		if (Tb < C)
			bkt(a, b + 1);
		Tb -= t[1][b];
	}
	else
	if (b > N)
	{
		Ta += t[0][a];
		if (Ta < C)
			bkt(a + 1, b);
		Ta -= t[0][a];
	}
	else
	{
		if (res[0][a] == res[1][b])
		{
			// make b wait
			Ta += t[0][a];
			Tprev = Tb;
			Tb = Ta;
			if (Ta < C)
				bkt(a + 1, b);
			Tb = Tprev;
			Ta -= t[0][a];

			// make a wait
			Tb += t[1][b];
			Tprev = Ta;
			Ta = Tb;
			if (Tb < C)
				bkt(a, b + 1);
			Ta = Tprev;
			Tb -= t[1][b];
		}
		else
		if (Ta + t[0][a] < Tb + t[1][b])
		{
			Ta += t[0][a];
			if (Ta < C)
				bkt(a + 1, b);
			Ta -= t[0][a];
		}
		else
		if (Ta + t[0][a] > Tb + t[1][b])
		{
			Tb += t[1][b];
			if (Tb < C)
				bkt(a, b + 1);
			Tb -= t[1][b];
		}
		else
		{
			Ta += t[0][a];
			Tb += t[1][b];
			bkt(a + 1, b + 1);
			Tb -= t[1][b];
			Ta -= t[0][a];
		}
	}
}

int main()
{
	freopen("js.in", "r", stdin);
	scanf("%d", &T);

	while (T--)
	{
		scanf("%d", &N);
		for (i = 0; i <= 1; i++)
			for (j = 1; j <= N; j++)
				scanf("%d %d", &res[i][j], &t[i][j]);
		
		C = INF;

		Ta = Tb = 0;
		bkt(1, 1);

		printf("%d\n", C);
		fprintf(stderr, "%d\n", C);
	}

	return 0;
}
