Mai intai trebuie sa te autentifici.
Cod sursa(job #3144041)
Utilizator | Data | 3 august 2023 21:35:18 | |
---|---|---|---|
Problema | Arbori indexati binar | Scor | 100 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 1.68 kb |
#include <fstream>
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");
const int N_MAX = 1e5;
const int FENWICK_TREE_DIM_MAX = N_MAX + 1;
const int LOG_MAX = 16;
template<typename T>
class FenwickTree{
private:
T bit[FENWICK_TREE_DIM_MAX]{};
int bitSize;
inline T leastSigmificantBit(int i){
return i & (-i);
}
public:
void build(int n, ifstream& fin){
bitSize = n;
T x;
for(int i = 1; i <= n; ++i){
fin >> x;
bit[i] += x;
if(i + leastSigmificantBit(i) <= bitSize)
bit[i + leastSigmificantBit(i)] += bit[i];
}
}
void update(int pos, T val){
while(pos <= bitSize){
bit[pos] += val;
pos += leastSigmificantBit(pos);
}
}
T query(int pos){
T sum = 0;
while(pos > 0){
sum += bit[pos];
pos -= leastSigmificantBit(pos);
}
return sum;
}
T query(int x, int y){
return query(y) - query(x - 1);
}
int find(T val){
int pos = 0;
T sum{};
for(int e = LOG_MAX; e >= 0; --e)
if(pos + (1 << e) <= bitSize && sum + bit[pos + (1 << e)] < val){
pos += 1 << e;
sum += bit[pos];
}
if(pos + 1 <= bitSize && query(pos + 1) == val)
++pos;
else
pos = -1;
return pos;
}
void print(){
for(int i = 0; i <= bitSize; ++i)
fout << bit[i] << ' ';
fout.put('\n');
}
};
FenwickTree<int> bit;
int main(){
int n, queries;
fin >> n >> queries;
bit.build(n, fin);
int type, a, b;
for(int i = 0; i < queries; ++i){
fin >> type;
if(!type){
fin >> a >> b;
bit.update(a, b);
}else if(type == 1){
fin >> a >> b;
fout << bit.query(a, b) << '\n';
}else{
fin >> a;
fout << bit.find(a) << '\n';
}
}
fin.close();
fout.close();
return 0;
}