#include #include using namespace std; using ll = long long; #define rep(i, n) for (int i = 0; i < (int)(n); i++) const ll INF = 1e18; void solve() { ll n, m; cin >> n >> m; vector> ab(m); rep(i, m) { ll a, b; cin >> a >> b, a--, b--; ab[i] = {a, b}; } vector c(n), w(10); rep(i, n) cin >> c[i], c[i]--; rep(i, 10) cin >> w[i]; ll q; cin >> q; vector> qs(q); rep(qi, q) { ll a, b; cin >> a >> b, a--, b--; qs[qi] = {a, b}; } vector ans(q, INF); rep(S, 1 << 10) { ll sumw = 0; atcoder::dsu d(n); rep(i, 10) if ((S >> i) & 1) sumw += w[i]; for (const auto &[a, b] : ab) { if (!d.same(a, b)) if ((S >> c[a]) & 1) if ((S >> c[b]) & 1) d.merge(a, b); } rep(qi, q) { const auto &[u, v] = qs[qi]; if (d.same(u, v)) { ans[qi] = min(ans[qi], sumw); } } } rep(qi, q) cout << (ans[qi] == INF ? -1 : ans[qi]) << '\n'; } int main() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); int T = 1; for (int t = 0; t < T; t++) { solve(); } return 0; }