#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define NMAX 333
#define INF 666666666

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

int res[2][NMAX], t[2][NMAX], sum[2][NMAX];
int i, j, k, a, b, c, Ta, Tb, N, C, T, sumA, sumB, nstates;

int randChoice(void)
{
	if (rand() % 2 == 0)
		return 0;
	else
		return 1;
}

int sum1Choice(void)
{
	if (Ta + sum[0][a] >= Tb + sum[1][b])
		return 0;
	else
		return 1;
}

int sum2Choice(void)
{
	if (Ta + sum[0][a] <= Tb + sum[1][b])
		return 0;
	else
		return 1;
}

int sum3Choice(void)
{
	if (sum[0][a] >= sum[1][b])
		return 0;
	else
		return 1;
}

int sum4Choice(void)
{
	if (sum[0][a] <= sum[1][b])
		return 0;
	else
		return 1;
}

int sum5Choice(void)
{
	if (sum[1][b] - sum[0][a + 1] >= sum[0][a] - sum[1][b + 1])
		return 0;
	else
		return 1;
}

int sum6Choice(void)
{
	if (sum[1][b] - sum[0][a + 1] <= sum[0][a] - sum[1][b + 1])
		return 0;
	else
		return 1;
}

int size1Choice(void)
{
	if (t[0][a] <= t[1][b])
		return 0;
	else
		return 1;
}

int size2Choice(void)
{
	if (t[0][a] >= t[1][b])
		return 0;
	else
		return 1;
}

int greedy(int choose(void))
{
	Ta = Tb = 0;
	a = b = 1;

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

			if (c == 0)
			{
				Ta += t[0][a];
				a++;
				Tb = Ta;
			}
			else
			{
				Tb += t[1][b];
				b++;
				Ta = Tb;
			}
		}
		else
		{
			if (Ta + t[0][a] < Tb + t[1][b])
			{
				Ta += t[0][a];
				a++;
			}
			else if (Tb + t[1][b] < Ta + t[0][a])
			{
				Tb += t[1][b];
				b++;
			}
			else
			{
				Ta += t[0][a];
				a++;
				Tb += t[1][b];
				b++;
			}
		}
	}

	while (a <= N)
	{
		Ta += t[0][a];
		a++;
	}

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

	return max(Ta, Tb);
}

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

	scanf("%d", &T);
	srand(time(NULL));

	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 <= 1; i++)
		{
			sum[i][N + 1] = 0;
			for (j = N; j >= 1; j--)
				sum[i][j] = t[i][j] + sum[i][j + 1];
		}

		C = INF;
		for (k = 1; k <= 200; k++)
			C=min(C, greedy(randChoice));

		C=min(C, greedy(sum1Choice));
		C=min(C, greedy(sum2Choice));
		C=min(C, greedy(sum3Choice));
		C=min(C, greedy(sum4Choice));
		C=min(C, greedy(sum5Choice));
		C=min(C, greedy(sum6Choice));
		C=min(C, greedy(size1Choice));
		C=min(C, greedy(size2Choice));

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

	return 0;
}
