#include #include #include using namespace std; class UnionFind { private: int n; vector par; int group_; public: UnionFind(int n) : n(n), par(n, -1), group_(n) {} int find(int x) { if (par[x] < 0) return x; vector lst; while (par[x] >= 0) { lst.push_back(x); x = par[x]; } for (int y : lst) { par[y] = x; } return x; } bool unite(int x, int y) { x = find(x); y = find(y); if (x == y) return false; if (par[x] > par[y]) swap(x, y); par[x] += par[y]; par[y] = x; group_--; return true; } int size(int x) { return -par[find(x)]; } bool same(int x, int y) { return find(x) == find(y); } int group() { return group_; } }; int main() { int n, m; cin >> n >> m; vector> ab(m, vector(2)); for (int i = 0; i < m; ++i) { cin >> ab[i][0] >> ab[i][1]; } vector C(n), W(10); for (int i = 0; i < n; ++i) { cin >> C[i]; C[i]--; } for (int i = 0; i < 10; ++i) { cin >> W[i]; } int t = 10; vector UF(1 << t, UnionFind(n)); vector cost(1 << t, 0); for (int bit = 0; bit < (1 << t); ++bit) { for (int i = 0; i < t; ++i) { if (bit >> i & 1) { cost[bit] += W[i]; } } } for (auto& edge : ab) { edge[0]--; edge[1]--; int bit = (1 << C[edge[0]]) | (1 << C[edge[1]]); for (int S = 0; S < (1 << t); ++S) { if ((S & bit) == bit) { UF[S].unite(edge[0], edge[1]); } } } int Q; cin >> Q; for (int q = 0; q < Q; ++q) { int x, y; cin >> x >> y; x--; y--; long long ans = cost[(1 << t) - 1] + 1; for (int S = 0; S < (1 << t); ++S) { if (UF[S].same(x, y)) { ans = min(ans, cost[S]); } } if (ans == cost[(1 << t) - 1] + 1) { ans = -1; } cout << ans << endl; } return 0; }