离线树状数组例题(待学习)

https://codeforces.ml/contest/1712/problem/E2

题解:

https://www.bilibili.com/video/BV1uB4y167ig?spm_id_from=333.1007.top_right_bar_window_view_later.content.click&vd_source=75ae018f8d1181302d7ea76b60c928f4

主要思路为:“离线?”计算k取1-r时的树状数组:记录i取1-r时的数量,然后对r的ask减去当前合法的数量(树状数组l~(r-2))

代码:

复制代码
#include<bits/stdc++.h>

#define fore(x,y,z) for(LL x=(y);x<=(z);x++)
#define forn(x,y,z) for(LL x=(y);x<(z);x++)
#define rofe(x,y,z) for(LL x=(y);x>=(z);x--)
#define rofn(x,y,z) for(LL x=(y);x>(z);x--)
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second

using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;

vector<int> factor[400100];
vector<PII> ask[200010];
LL ans[100010];
LL tr[200010];


int lowbit(int x)
{
    return x & (-x);
}
int add(int x, int c)
{
    for (int i = x; i <= 200000; i += lowbit(i))
    {
        tr[i] += c;
    }
    return 0;

}
LL sum(int x)
{
    LL res = 0;
    for (int i = x; i > 0; i -= lowbit(i))
        res += tr[i];
    return res;

}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    for (int i = 1; i <= 200010; i++)
    {
        for (int j = i; j <= 400020; j += i)
            factor[j].push_back(i);
    }
    int T = 1;
    cin >> T;
    int a, b;
    for(int i=1;i<=T;i++)
    {
        cin >> a >> b;
        ask[b].push_back({ a,i });
        LL x = b - a + 1;
        ans[i] = x * (x - 1)*(x - 2) / 6;

    }
    for (int k = 1; k <= 200000; k++)
    {
        for (auto i : factor[2 * k])
        {
            if (i == k)
                break;
            int cnt = 0;
            for (auto j : factor[2 * k])
            {
                if (j == k)
                    break;
                if (j <= i)
                    continue;
                if (k%j == 0 && k%i == 0)
                    cnt++;
                else if (i + j > k)
                    cnt++;

            }
            add(i, cnt);
        }
        for (auto[l, i] : ask[k])
        {
            ans[i] -= sum(k - 2) - sum(l - 1);
        }
    }
    for (int i = 1; i <= T; i++)
    {
        cout << ans[i] << endl;
    }
    return 0;
}
View Code
复制代码

 

posted @   80k  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示