优化Fenwick Tree(C ++)

时间:2015-10-30 16:22:05

标签: c++ fenwick-tree

我有以下Fenwick Tree算法的实现。

#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<=5000000Q<=5000000处理。它应该能够在9秒内运行。但在提交此问题后,我得到了超时限制(TLE)的判决。我已尝试过每一项措施来优化此代码,但无济于事,它仍然给了我TLE。我怎么可能优化这段代码,以便它可以在9秒内运行。非常感谢你。

1 个答案:

答案 0 :(得分:0)

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

int main() {
    cin.tie(nullptr);
    std::ios::sync_with_stdio(false);
    ...
相关问题