이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int N, M, Q, timer;
vector<int> sz, pos, dep, par, top;
vector<ll> bit;
vector<vector<int>> adj;
void add(int i, ll s) {
for (i++; i <= N; i += i & -i) {
bit[i] += s;
}
}
ll sum(int i) {
ll s = 0;
for (; i; i -= i & -i) s += bit[i];
return s;
}
void init(int x) {
sz[x] = 1;
for (auto &y : adj[x]) {
adj[y].erase(find(adj[y].begin(), adj[y].end(), par[y] = x));
dep[y] = dep[x] + 1;
init(y);
sz[x] += sz[y];
if (sz[y] > sz[adj[x][0]]) swap(y, adj[x][0]);
}
}
void dfs(int x) {
pos[x] = timer++;
for (auto y : adj[x]) {
top[y] = y == adj[x][0] ? top[x] : y;
dfs(y);
}
}
ll path(int x, int y) {
ll s = 0;
for (; top[x] != top[y]; x = par[top[x]]) {
if (dep[top[x]] < dep[top[y]]) swap(x, y);
s += sum(pos[x] + 1) - sum(pos[top[x]]);
}
if (dep[x] > dep[y]) swap(x, y);
return s += sum(pos[y] + 1) - sum(pos[x] + 1);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> N >> M >> Q;
sz.resize(N);
pos.resize(N);
dep.resize(N);
adj.resize(N);
top.resize(N);
par.resize(N, -1);
bit.resize(N + 1);
vector<pair<int, int>> edges(N - 1);
for (int i = 0; i < N - 1; i++) {
int a, b;
cin >> a >> b;
a--, b--;
edges[i] = {a, b};
adj[a].push_back(i);
adj[b].push_back(i);
}
vector<int> w(N - 1); {
function<void(int, int)> dfs = [&](int x, int p) {
for (auto &y : adj[x]) {
int i = y;
auto [u, v] = edges[y];
y = x ^ u ^ v;
if (y == p) continue;
w[i] = y;
dfs(y, x);
}
};
dfs(0, -1);
}
init(0); dfs(0);
vector<pair<int, int>> ch(M);
for (int i = 0; i < M; i++) {
int e, s;
cin >> e >> s; e--;
ch[i] = {s, w[e]};
}
sort(ch.begin(), ch.end());
vector<int> S(Q), T(Q), X(Q), ans(Q);
vector<ll> Y(Q);
for (int i = 0; i < Q; i++) {
cin >> S[i] >> T[i] >> X[i] >> Y[i];
S[i]--, T[i]--;
}
vector<int> lo(Q), hi(Q, M);
while (1) {
bool end = 1;
vector<vector<int>> v(M + 1);
for (int i = 0; i < Q; i++) {
if (lo[i] < hi[i]) {
end = 0;
v[(lo[i] + hi[i] + 1) / 2].push_back(i);
}
}
if (end) break;
bit.assign(N + 1, 0);
for (int i = 0; i <= M; i++) {
for (auto j : v[i]) {
path(S[j], T[j]) <= Y[j] ? lo[j] = i : hi[j] = i - 1;
}
if (i < M) {
auto [s, j] = ch[i];
add(pos[j], s);
}
}
}
vector<vector<int>> a(M + 1);
for (int i = 0; i < Q; i++) {
a[lo[i]].push_back(i);
}
bit.assign(N + 1, 0);
for (int i = M; i >= 0; i--) {
if (i < M) {
auto [s, j] = ch[i];
add(pos[j], 1);
}
for (auto j : a[i]) {
ans[j] = max<ll>(-1, X[j] - path(S[j], T[j]));
}
}
for (int i = 0; i < Q; i++) cout << ans[i] << "\n";
return 6/22;
}
# | 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... |