Optimizing Fenwick Tree (C++)

Optimizing Fenwick Tree (C++)

本文关键字:C++ Tree Fenwick Optimizing      更新时间:2023-10-16

我有以下芬威克树算法的实现。

#include <bits/stdc++.h>
#define LSOne(S) (S & (-S))
using namespace std;
typedef long long int L;
int rsq(L b, L x[]){
    int sum=0;
    for(; b; b-=LSOne(b)) sum+=x[b];
    return sum;
}
void adjust(int k, L v, L x[], int n){
    for(; k<=n;k+=LSOne(k)) x[k]+=v;
}
int main(){
    int n,q; cin>>n>>q;
    L ft[n+1]; memset(ft,0,sizeof(ft));
    while(q--){
        char x; int i,j; cin>>x;
        if(x=='+'){
            cin>>i>>j;
            adjust(i+1,j,ft,n);
        } else if(x=='?') {
            cin>>i;
            cout<<rsq(i,ft)<<endl;
        }
    }
}

该程序应该能够为N<=5000000运行并处理Q<=5000000。它应该能够在9秒以下运行。但在提交这个问题后,我得到了超过时间限制(TLE)的裁决。我已经尝试了各种方法来优化这个代码,但没有成功,它仍然给了我TLE。我怎么可能优化这个代码,使它可以在9秒内运行。非常感谢。

从stdin读取500000行所需的时间可能是个问题。您是否尝试优化IO缓冲:

int main() {
    cin.tie(nullptr);
    std::ios::sync_with_stdio(false);
    ...