// TODO #ifdef NACHIA #define _GLIBCXX_DEBUG #else // disable assert #define NDEBUG #endif #include #include #include #include #include using namespace std; using ll = long long; const ll INF = 1ll << 60; #define REP(i,n) for(ll i=0; i using V = vector; template void chmax(A& l, const B& r){ if(l < r) l = r; } template void chmin(A& l, const B& r){ if(r < l) l = r; } void testcase(){ ll N, K; cin >> N >> K; V A(N); REP(i,N) cin >> A[i]; V> adj(N); REP(i,N){ ll u,v; cin >> u >> v; u--; v--; adj[u].insert(v); adj[v].insert(u); } auto remedge = [&](ll u, ll v){ adj[u].erase(v); adj[v].erase(u); }; ll offset = 0; { V que; REP(i,N) if(adj[i].size() == 1) que.push_back(i); while(que.size()){ ll v = que.back(); que.pop_back(); ll w = adj[v].begin().operator*(); if(0 < A[v] && A[v] < K){ cout << "-1\n"; return; } if(0 < A[v]) offset += (A[v] + (K * 2 - 1)) / (K * 2); A[w] -= A[v]; A[v] = 0; if(A[w] < 0){ cout << "-1\n"; return; } remedge(v, w); if(adj[w].size() == 1) que.push_back(w); } } V seq, B; REP(i,N) if(adj[i].size()){ ll v = i; while(adj[v].size()){ ll w = adj[v].begin().operator*(); seq.push_back(w); B.push_back(A[w]); remedge(v, w); v = w; } } // cout << offset << endl; // for(auto a : B) cout << a << " "; cout << endl; ll M = B.size(); if(M % 2 == 1){ ll ans = offset; V Q(M); REP(i,M) Q[M-1] += (B[i] * (i % 2 ? -1 : 1)); if(Q[M-1] % 2 != 0){ cout << "-1\n"; return; } Q[M-1] /= 2; REP(i,M-1) Q[i] = B[i] - Q[(i+M-1)%M]; if(Q[M-1] != B[M-1] - Q[M-2]){ cout << "-1\n"; return; } for(ll q : Q) if(q < 0 || (0 < q && q < K)){ cout << "-1\n"; return; } for(ll q : Q){ if(0 < q) ans += (q + (K * 2 - 1)) / (K * 2); } cout << ans << "\n"; return; } REP(i,M-1) B[i+1] -= B[i]; if(B[M-1] != 0){ cout << "-1\n"; return; } V G, H; REP(i,M) (i%2 == 0? G : H).push_back(B[i]); sort(G.begin(), G.end()); sort(H.begin(), H.end()); ll ans = INF; REP(h,2){ ll g = G[0]; auto nG = G; auto nH = H; for(auto& a : nG) a -= g; for(auto& a : nH) a += g; ll tmp = 0; for(ll q : nG) if(q < 0 || (0 < q && q < K)) tmp = INF; for(ll q : nH) if(q < 0 || (0 < q && q < K)) tmp = INF; for(ll q : nG) if(0 < q) tmp += (q + (K * 2 - 1)) / (K * 2); for(ll q : nH) if(0 < q) tmp += (q + (K * 2 - 1)) / (K * 2); chmin(ans, offset + tmp); swap(G, H); } if(ans > INF / 2) ans = -1; cout << ans << "\n"; } int main(){ cin.tie(0)->sync_with_stdio(0); testcase(); return 0; }