제출 #1235590

#제출 시각아이디문제언어결과실행 시간메모리
1235590JooDdaeTwo Currencies (JOI23_currencies)C++20
100 / 100
322 ms71848 KiB
#include <bits/stdc++.h> using namespace std; using ll = long long; #define mid ((l+r) >> 1) struct Node { ll s; int c, l, r; } t[5005005]; int r[100100], cnt; int n, m, k, x[100100], y[100100], a[100100], c[100100], lev[100100], sp[100100][20]; vector<int> v[100100], in[100100]; vector<array<int, 2>> C; int update(int u, int id, int l = 0, int r = m-1) { if(id < l || r < id) return u; int x = ++cnt; t[x] = t[u], t[x].s += C[id][0], t[x].c++; if(l == r) return x; t[x].l = update(t[x].l, id, l, mid); t[x].r = update(t[x].r, id, mid+1, r); return x; } int find(int a, int b, int c, ll s, int l = 0, int r = m-1) { if(t[b].c+t[c].c-t[a].c*2 <= 1) return s < t[b].s+t[c].s-t[a].s*2; ll ls = t[t[b].l].s+t[t[c].l].s-t[t[a].l].s*2; if(ls > s) return find(t[a].l, t[b].l, t[c].l, s, l, mid) + t[t[b].r].c+t[t[c].r].c-t[t[a].r].c*2; return find(t[a].r, t[b].r, t[c].r, s-ls, mid+1, r); } void dfs(int u, int p) { sp[u][0] = p, lev[u] = lev[p]+1; for(int i=1;i<20;i++) sp[u][i] = sp[sp[u][i-1]][i-1]; r[u] = r[p]; for(auto i : in[u]) if(x[a[i]] == p || y[a[i]] == p) r[u] = update(r[u], c[i]); for(auto x : v[u]) if(x != p) dfs(x, u); } int lca(int x, int y) { if(lev[x] < lev[y]) swap(x, y); for(int i=0;i<20;i++) if((1 << i) & (lev[x]-lev[y])) x = sp[x][i]; if(x == y) return x; for(int i=19;i>=0;i--) if(sp[x][i] != sp[y][i]) x = sp[x][i], y = sp[y][i]; return sp[x][0]; } int main() { cin.tie(0)->sync_with_stdio(0); cin >> n >> m >> k; for(int i=1;i<n;i++) { cin >> x[i] >> y[i]; v[x[i]].push_back(y[i]); v[y[i]].push_back(x[i]); } for(int i=1;i<=m;i++) { cin >> a[i] >> c[i]; C.push_back({c[i], i}); in[x[a[i]]].push_back(i); in[y[a[i]]].push_back(i); } sort(C.begin(), C.end()); for(int i=0;i<m;i++) c[C[i][1]] = i; dfs(1, 0); while(k--) { ll s, e, G, S; cin >> s >> e >> G >> S; int L = lca(s, e); cout << max(G-find(r[L], r[s], r[e], S), -1ll) << "\n"; } }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...