Pagini recente » Cod sursa (job #1888324) | Cod sursa (job #2046947) | Cod sursa (job #83949) | Cod sursa (job #1382887) | Cod sursa (job #2315076)
#include <bits/stdc++.h>
using namespace std;
unsigned int aib[100001];
int mostUnsignificantBit (int x) {
return x & (-x);
}
void update (int n, int position, unsigned int value) {
while (position <= n) {
aib[position] += value;
position += mostUnsignificantBit(position);
}
}
unsigned int sumQuery (int position) {
unsigned int currentSum = 0;
while (position) {
currentSum += aib[position];
position -= mostUnsignificantBit(position);
}
return currentSum;
}
unsigned int intervalSum (int left, int right) {
return sumQuery(right) - sumQuery(left - 1);
}
int findPosition (unsigned int currentSum, int n) {
int currentPosition = 0;
for (int power = 20; power >= 0; --power) {
if (currentPosition + (1 << power) <= n and (aib[currentPosition + (1 << power)] <= currentSum)) {
currentSum -= aib [currentPosition + (1 << power)];
currentPosition += (1 << power);
}
}
return (currentSum == 0 and currentPosition ? currentPosition : - 1);
}
int main() {
ifstream fin ("aib.in");
ofstream fout ("aib.out");
int n, m;
fin >> n >> m;
for (int i = 1; i <= n; ++i) {
unsigned int x;
fin >> x;
update(n, i, x);
}
for (int i = 1; i <= m; ++i) {
int type;
fin >> type;
if (type == 0) {
int position;
unsigned int value;
fin >> position >> value;
update(n, position, value);
}
if (type == 1) {
int left, right;
fin >> left >> right;
fout << intervalSum(left, right) << '\n';
}
if (type == 2) {
unsigned int currentSum;
fin >> currentSum;
fout << findPosition(currentSum, n) << '\n';
}
}
return 0;
}