import java.util.*;

public class Panda {
	int[] memo = new int[1<<18];
	int[] cost, conf, depend, lines;
	int N, inf = 100000000;

	int rec(int def){
		if (def==(1<<N)-1) return 0;
		if (memo[def]!=-1) return memo[def];

		int ret = inf;
		for (int i=0; i<N; i++) if ((def&(1<<i))==0){
			if ((depend[i] & def) != depend[i]) continue;
			int moved = lines[(((1<<N)-1)^def) & ((1<<i)-1)];
			ret = Math.min(ret, moved*cost[i] + rec(def|(1<<i)));
		}
		return memo[def] = ret;
	}

	void solve(){
		Scanner scan = new Scanner(System.in);
		int T = scan.nextInt();
		while (T-- > 0){
			N = scan.nextInt();
			cost = new int[N];
			for (int i=0; i<N; i++) cost[i] = scan.nextInt();
			depend = new int[N];
			for (int i=0; i<N; i++)
				for (int C = scan.nextInt(); C-- > 0;){
					int F = scan.nextInt() - 1;
					if (i!=F) depend[i] |= 1 << F;
				}
			conf = new int[N];
			for (int i=0; i<N; i++) conf[i] = scan.nextInt()-1;

			lines = new int[1<<N];
			for (int i=0; i<(1<<N); i++){
				int mask = 0, sum = 0;
				for (int j=0; j<N; j++)
					if ((i&(1<<j))!=0){
						sum += cost[conf[j]];
						mask |= 1<<conf[j];
					}
				lines[mask] = sum;
			}

			Arrays.fill(memo,-1);
			System.out.printf("%d\n",rec(0)==inf?-1:rec(0));
		}
	}

	public static void main(String[] args){
		new Panda().solve();
	}
}
