from collections import defaultdict class UnionFind(): def __init__(self, n): self.n = n self.root = [-1]*(n+1) self.rank = [0]*(n+1) def find(self, x): if(self.root[x] < 0): return x else: self.root[x] = self.find(self.root[x]) return self.root[x] def unite(self, x, y): x = self.find(x) y = self.find(y) if(x == y): return elif(self.rank[x] > self.rank[y]): self.root[x] += self.root[y] self.root[y] = x else: self.root[y] += self.root[x] self.root[x] = y if(self.rank[x] == self.rank[y]): self.rank[y] += 1 def same(self, x, y): return self.find(x) == self.find(y) def size(self, x): return -self.root[self.find(x)] def roots(self): return [i for i, x in enumerate(self.root) if x < 0] def group_size(self): return len(self.roots()) def group_members(self): group_members = defaultdict(list) for member in range(self.n): group_members[self.find(member)].append(member) return group_members N,M = map(int,input().split()) G = [[] for i in range(N)] E = [] for i in range(M): A,B = map(int,input().split()) A -= 1 B -= 1 G[A].append(B) G[B].append(A) E.append((A,B)) C = list(map(int,input().split())) for i in range(N): C[i] -= 1 W = list(map(int,input().split())) # bit CC = [0 for i in range(1<<10)] for i in range(1<<10): for j in range(10): if (i >> j) & 1: CC[i] += W[j] UF = [UnionFind(N) for i in range(1<<10)] for i in range(1<<10): for u,v in E: if (i >> C[u]) & 1 and (i >> C[v]) & 1: UF[i].unite(u,v) inf = 10**12 Q = int(input()) for _ in range(Q): u,v = map(int,input().split()) u -= 1 v -= 1 ans = inf for bit in range(1<<10): if UF[bit].same(u,v): ans = min(ans,CC[bit]) if ans == inf: ans = -1 print(ans)