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

#define MAXN 18

int T,C,F,n,cost[MAXN],conf[MAXN];
int lines[1<<MAXN][MAXN];
int dp[MAXN+1][1<<MAXN];
int depend[MAXN];
int inf = 100000000;

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(dp[0], 0, sizeof(dp[0]));
		for (int i=1; i<=n; i++)
			for (int j=0; j<(1<<n); j++)
				dp[i][j] = inf;

		memset(lines,0,sizeof(lines));
		for (int def=0; def<(1<<n); def++)
			for (int i=0; i<n; i++) if ((def&(1<<i))==0)
				for (int j=0; j<n && conf[j]!=i; j++)
					if ((def&(1<<conf[j]))==0) lines[def][i] += cost[conf[j]];

		for (int idx=0; idx<n; idx++){
			for (int def=0; def<(1<<n); def++) if (dp[idx][def]<inf) {
				for (int i=0; i<n; i++) if ((def&(1<<i))==0 && (depend[i]&def)==depend[i]){
					int cur = lines[def][i] * cost[i] + dp[idx][def];
					int &next = dp[idx+1][def|(1<<i)];
					if (cur < next) next = cur;
				}
			}
		}
				
		int res = dp[n][(1<<n)-1];
		printf("%d\n",res==inf? -1 : res);
	}
}
