#21. Trygub numbers 动态维护大数

· · 算法·理论

本文将详细揭秘 Trygub numbers,来自一篇 codeforces 上的一篇 blog。

动态维护 b 进制大数 N,需要做到:

  • 给定 |x|,|y|\le n,将 xb^y 加到 N。
  • 给定 k,输出 N 的第 k 位的值。
  • 判断 N 是正数还是负数或者 0。

首先这显然可以用线段树等数据结构来维护进位或者借位,但是这太麻烦了。

考虑跳出平常的逻辑思维,每一位上的值域不在是 [0,b) 而是 (-b,b)。这样当我们一个数变成 \pm b 时,直接加到下一位上,并且这一位归为 0。发现了什么?这样我们在减法的时候,就不会出现大规模的借位,借位的复杂度和进位相同都变成了均摊。

update:有人提问为什么要 mp.erase(y),那看来是我没讲清楚。

就,我们维护的其实是 N=\sum_{i=1}^{t}x_ib^{y_i}。其中 x_i\in (-b,b)。对于查询操作,对于比其前一位有值的位置如果是负数,就需要从这里借位,

所有这些成立均因为 \sum_{i=0}^{n-1}x_ib^{i}<b^{n}。然后如果这一位是负数,那么必然可以从前面的位借来 b^{...},所以直接取模即可。

板子题:#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;
}