#21. Trygub numbers 动态维护大数
本文将详细揭秘 Trygub numbers,来自一篇 codeforces 上的一篇 blog。
动态维护
b 进制大数N ,需要做到:
- 给定
|x|,|y|\le n ,将xb^y 加到N 。- 给定
k ,输出N 的第k 位的值。- 判断
N 是正数还是负数或者0 。
首先这显然可以用线段树等数据结构来维护进位或者借位,但是这太麻烦了。
考虑跳出平常的逻辑思维,每一位上的值域不在是
update:有人提问为什么要 mp.erase(y),那看来是我没讲清楚。
就,我们维护的其实是
所有这些成立均因为
板子题:#2302. 「NOI2017」整数 - 题目 - LibreOJ (loj.ac)
细节可以看代码,非常好理解。这道题采用了压位,复杂度线性对数。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template <typename T>
void read(T &x)
{
T sgn = 1;
char ch = getchar();
for (; !isdigit(ch); ch = getchar()) if (ch == '-') sgn = -1;
for (x = 0; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0';
x *= sgn;
}
const int B = 30;
const ll base = 1 << B;
struct trygub_numbers
{
map<int, ll> mp;
void add(ll x, int y)
{
mp[y] += x;
int t;
do
{
t = mp[y] / base;
mp[y + 1] += t;
mp[y] -= t * base;
if (!mp[y]) mp.erase(y);
y++;
} while (t);
if (!mp[y]) mp.erase(y);
}
ll qry(int k)
{
auto it = mp.lower_bound(k);
ll res = it == mp.end() || it -> first > k ? 0 : it -> second;
if (it != mp.begin() && prev(it) -> second < 0) res--;
return (res % base + base) % base;
}
}N;
int n, t1, t2, t3;
int main()
{
read(n); read(t1); read(t2); read(t3);
for (int i = 1, op, a, b; i <= n; i++)
{
read(op); read(a);
if (op == 1) read(b), N.add(1ll * a * (1 << (b % B)), b / B);
else
{
ll res= N.qry(a / B);
printf("%lld\n", (res >> (a % B)) & 1);
}
}
return 0;
}