#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, tsa, tsb, N, C, T, sumA, sumB, nstates;

int main()
{
	freopen("js.in", "r", stdin);
	freopen("js.out", "w", stdout);

	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]);
		
		for (i = 0; i <= N; i++)
			for (j = 0; j <= N; j++)
				Tmin[i][j] = INF;

		Tmin[0][0] = 0;
		C = INF;

		nstates = 0;
		for (i = 0; i <= N; i++)
			for (j = 0; j <= N; j++)
				if (Tmin[i][j] < INF)
				{
					nstates++;

					a = i + 1;
					b = j + 1;
					tsa = tsb = 0;

					while (a <= N && b <= N)
					{
						if (res[0][a] == res[1][b])
							break;

						if (tsa + t[0][a] < tsb + t[1][b])
						{
							tsa += t[0][a];
							a++;
						}
						else if (tsb + t[1][b] < tsa + t[0][a])
						{
							tsb += t[1][b];
							b++;
						}
						else
						{
							tsa += t[0][a];
							a++;
							tsb += t[1][b];
							b++;
						}
					}

					if (a > N || b > N)
					{
						while (a <= N)
						{
							tsa += t[0][a];
							a++;
						}

						while (b <= N)
						{
							tsb += t[1][b];
							b++;
						}

						C = min(C, max(Tmin[i][j] + tsa, Tmin[i][j] + tsb));
					}
					else
					{
						Tmin[a-1][b] = min(Tmin[a-1][b], Tmin[i][j] + tsb + t[1][b]);
						Tmin[a][b-1] = min(Tmin[a][b-1], Tmin[i][j] + tsa + t[0][a]);
					}
				}

		printf("%d\n", C);

		sumA = 0;
		for (i = 1; i <= N; i++)
			sumA += t[0][i];

		sumB = 0;
		for (i = 1; i <= N; i++)
			sumB += t[1][i];

		fprintf(stderr, "C=%d, sumA=%d, sumB=%d, nstates=%d/%d, #tests left=%d\n", C, sumA, sumB, nstates, N * N, T);
	}

	return 0;
}
