科技题
参考资料:https://codeforc.es/blog/entry/115626。代码实现上比文中示例更加精细,从而得到了更优的复杂度。
这是一个只需要 std::map 的低门槛单 略巨大。
我们考虑直接暴力维护这个二进制数,暴力加,暴力进位,查询就直接查,那么在加法不带负数的情况下实际上复杂度是很对的——为什么?我们考虑
那么我们回到原题,
至于求给定位上的值,这个事情是显而易见的,我们只需要关心一下给定位上的数码和他的低位中最高位的那一个非 0 数码就可以了。我们可以用 std::map 维护非 0 数码集合,这样就可以快速找到前驱了。
#include <bits/stdc++.h>
using namespace std;
int n, t1, t2, t3;
map<int, int> mp;
void add(int v, int p) {
mp[p] += v;
while (true) {
int d = mp[p] / 2;
if (!(mp[p] %= 2)) mp.erase(p);
if (!d) return;
mp[++p] += d;
}
}
int query(int p) {
auto it = mp.lower_bound(p);
int v = it != mp.end() && it->first == p ? it->second & 1 : 0;
if (it != mp.begin()) v ^= !~prev(it)->second;
return v;
}
signed main() {
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n >> t1 >> t2 >> t3;
for (int op, x, y; n; --n)
if (cin >> op >> x, op == 1)
cin >> y, add(x, y);
else
cout << query(x) << '\n';
return cout << flush, 0;
}
现在我们发现查询的复杂度已经控制在了一个 emplace_hint 解决,单次插入的均摊复杂度是常数的。
于是我们的代码就优化到一个
#include <bits/stdc++.h>
using namespace std;
int n, t1, t2, t3;
map<int, int> mp;
void add(int v, int p) {
auto it = mp.emplace(p, 0).first;
it->second += v;
while (true) {
auto [d, f] = div(it->second, 2);
auto nit = it;
if (d) {
it = mp.emplace_hint(it, ++p, 0);
it->second += d;
}
if (!f)
mp.erase(nit);
else
nit->second = f;
if (!d) return;
}
}
int query(int p) {
auto it = mp.lower_bound(p);
int v = it != mp.end() && it->first == p ? it->second & 1 : 0;
if (it != mp.begin()) v ^= !~prev(it)->second;
return v;
}
signed main() {
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n >> t1 >> t2 >> t3;
for (int op, x, y; n; --n)
if (cin >> op >> x, op == 1)
cin >> y, add(x, y);
else
cout << query(x) << '\n';
return cout << flush, 0;
}
建议降蓝。