解題思路
以米粉島s為根,初始每點應稅航線數是深度。DFS給每個節點tin、tout,使子樹恰好對應半開區間[tin,tout)。
一條邊免稅,只有該邊較深端點的整個子樹需要少付一枚。因此在Fenwick差分陣列的tin加−1、tout加+1。
出貨到y時,Fenwick前綴和給出所有祖先免稅邊的總減量,加上depth[y]即剩餘稅邊數,再乘鳳梨數x。邊是樹的唯一路徑,因此每條免稅影響恰好一次。
O(n+(t+w)log n)時間、O(n)空間;答案用64位元。 Python一次讀入另佔O(輸入文字長度)空間。
Step-by-step animation
示例:1—2—3,以1為根,深度0、1、2。
步驟 1 / 3
初始鏈
1—2—3,以1為根,深度0、1、2。
d1=0
d2=1
d3=2
- 出貨3顆到3
- 6
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, s, t, w;
cin >> n >> s >> t >> w;
--s;
vector<vector<pair<int, int>>> g(n);
for (int i = 1, u, v; i < n; i++) {
cin >> u >> v;
--u;
--v;
g[u].push_back({v, i});
g[v].push_back({u, i});
}
vector<int> tin(n), tout(n), dep(n), child(n);
int timer = 0;
vector<array<int, 3>> st = {{s, -1, 0}};
while (!st.empty()) {
auto [u, p, exit] = st.back();
st.pop_back();
if (exit) {
tout[u] = timer;
continue;
}
tin[u] = timer++;
st.push_back({u, p, 1});
for (auto [v, e] : g[u])
if (v != p) {
dep[v] = dep[u] + 1;
child[e] = v;
st.push_back({v, u, 0});
}
}
vector<int> b(n + 2);
auto add = [&](int p, int x) {
for (++p; p <= n + 1; p += p & -p)
b[p] += x;
};
auto sum = [&](int p) {
int z = 0;
for (++p; p; p -= p & -p)
z += b[p];
return z;
};
for (int i = 0; i < t + w; i++) {
int k;
cin >> k;
if (k == 1) {
long long x;
int y;
cin >> x >> y;
--y;
cout << x * (dep[y] + sum(tin[y])) << '\n';
} else {
int e;
cin >> e;
int v = child[e];
add(tin[v], -1);
add(tout[v], 1);
}
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。