This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include "bits/stdc++.h"
using namespace std;
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define F0R(i, a) FOR(i, 0, a)
#define ROF(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define R0F(i, a) ROF(i, 0, a)
#define ar array
#define all(v) (v).begin(), (v).end()
#define sz(v) static_cast<int>(v.size())
typedef vector<int> vi;
typedef long long ll;
const int N = 1e5, L = 17, N_ = N * 20;
int ct[N_], lc[N_], rc[N_], tt;
ll sm[N_];
vi vc;
int copy(int k) {
tt++;
ct[tt] = ct[k], lc[tt] = lc[k], rc[tt] = rc[k], sm[tt] = sm[k];
return tt;
}
void upd(int& k, int l, int r, int i) {
k = copy(k);
sm[k] += vc[i], ct[k]++;
if (l < r) {
int m = (l + r) / 2;
if (i <= m)
upd(lc[k], l, m, i);
else
upd(rc[k], m + 1, r, i);
}
}
int get(int ki, int kj, int kp, int l, int r, ll y) {
if (l == r)
return min((ll)(ct[ki] + ct[kj] - 2 * ct[kp]), y / vc[l]);
else {
int m = (l + r) / 2;
ll ls = sm[lc[ki]] + sm[lc[kj]] - 2 * sm[lc[kp]];
if (ls <= y)
return ct[lc[ki]] + ct[lc[kj]] - 2 * ct[lc[kp]] +
get(rc[ki], rc[kj], rc[kp], m + 1, r, y - ls);
else
return get(lc[ki], lc[kj], lc[kp], l, m, y);
}
}
vi g[N], ad[N];
int p[L][N], d[N], gc[N], tr[N];
void dfs(int i) {
FOR(l, 1, L) p[l][i] = p[l - 1][p[l - 1][i]];
for (int j : g[i])
if (p[0][i] != j) {
p[0][j] = i;
d[j] = d[i] + 1;
dfs(j);
}
}
void bld(int i) {
for (int c : ad[i]) upd(tr[i], 0, sz(vc) - 1, c);
gc[i] += sz(ad[i]);
for (int j : g[i])
if (p[0][i] != j) {
tr[j] = tr[i];
gc[j] = gc[i];
bld(j);
}
}
int lca(int i, int j) {
if (d[i] < d[j]) swap(i, j);
int k = d[i] - d[j];
F0R(l, L) if (k >> l & 1) i = p[l][i];
if (i == j) return i;
R0F(l, L) if (p[l][i] != p[l][j]) i = p[l][i], j = p[l][j];
return p[0][i];
}
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin.exceptions(cin.failbit);
int n, m, q;
cin >> n >> m >> q;
static ar<int, 2> ed[N - 1];
F0R(h, n - 1) {
int i, j;
cin >> i >> j, i--, j--;
ed[h] = {i, j};
g[i].push_back(j), g[j].push_back(i);
}
dfs(0);
F0R(h, n - 1)
if (p[0][ed[h][0]] == ed[h][1]) swap(ed[h][0], ed[h][1]);
F0R(h, m) {
int e, c;
cin >> e >> c, e--;
ad[ed[e][1]].push_back(c);
vc.push_back(c);
}
sort(all(vc));
vc.erase(unique(all(vc)), end(vc));
F0R(i, n) for (int& c : ad[i]) c = lower_bound(all(vc), c) - begin(vc);
bld(0);
F0R(h, q) {
int i, j, x;
ll y;
cin >> i >> j >> x >> y, i--, j--;
int p = lca(i, j);
x -= gc[i] + gc[j] - 2 * gc[p] - get(tr[i], tr[j], tr[p], 0, sz(vc) - 1, y);
cout << max(x, -1) << '\n';
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |