Optimizing Fenwick Tree (C++)
Optimizing Fenwick Tree (C++)
我有以下芬威克树算法的实现。
#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);
...
相关文章:
- 使用 boost::p roperty_tree::p tree 如何获取特定键的值
- Boost R-Tree中的最小边界矩形计算
- C++ EXC_BAD_ACCESS (Binary Tree)
- Boost::p tree - 访问列表中包含的属性树节点
- Deserilizing n-ary tree
- Balancing KD Tree
- 如何填充'Tree'结构'Declaratively'
- 为什么qmap使用skiplist而不是ob rb-tree
- 避免在节点中添加重复的子级,使用 Kasper Peeters 的 Tree.hh 库
- SPOJ GSS1 WA - Segment tree
- Flattening the tree
- C++ AVL Tree Deletion
- RedBlack and AVL tree c++
- C++中已经有为 LinkedList、HashMap、Tree 等编写的类
- boost::p roperty_:tree - 解析和处理数据
- making tree with unordered_map
- AVL Tree in C++ Exception
- 使用 boost::p roperty_tree::p tree 将注释写入 ini 文件
- C++将具有非常相关数据的类 Tree 拆分为两个类
- 分段故障即将"Insertion in Binary Search tree." #