#include <stdio.h>
#include <string.h>

#define MAXN 18

int T,C,F,N,cost[MAXN],conf[MAXN],depend[MAXN];
int memo[1<<MAXN], inf = 100000000;

int rec(int def){
	if (def==(1<<N)-1) return 0;
	int &ret = memo[def];
	if (ret!=-1) return ret; else ret = inf;
	for (int i=0; i<N; i++) if ((def&(1<<i))==0){
		if ((depend[i] & def) != depend[i]) continue;

		int lines = 0;
		for (int j=0; j<N && conf[j]!=i; j++)
			if ((def&(1<<conf[j]))==0) lines += cost[conf[j]];
		int ccost = lines * cost[i] + rec(def | (1<<i));
		if (ccost < ret) ret = ccost;
	}
	return ret;
}

int main(){
	scanf("%d",&T);
	while (T--){
		scanf("%d",&N);
		for (int i=0; i<N; i++)
			scanf("%d",&cost[i]);

		memset(depend,0,sizeof(depend));
		for (int i=0; i<N; i++)
			for (scanf("%d",&C); C--; ){
				scanf("%d",&F);
				if (i!=F-1) depend[i] |= 1<<(F-1);
			}

		for (int i=0; i<N; i++)
			scanf("%d",&conf[i]), conf[i]--;

		memset(memo,-1,sizeof(memo));
		int res = rec(0);
		printf("%d\n",res==inf? -1 : res);
	}
}
