#include<bits/stdc++.h>
using namespace std;
struct node;
node *newNode();
struct node {
long long lv, rv, sum;
int count;
node *left, *right;
node() : left(NULL), right(NULL), count(0), sum(0) {}
void extend() {
if (!left) {
long long m = (lv + rv) / 2;
left = newNode();
right = newNode();
left->lv = lv;
left->rv = m;
right->lv = m + 1;
right->rv = rv;
}
}
long long getSum(long long l, long long r) {
if (r < lv || rv < l || !sum) {
return 0;
}
if (l <= lv && rv <= r) {
return sum;
}
extend();
return left->getSum(l, r) + right->getSum(l, r);
}
int getCount(long long l, long long r) {
if (r < lv || rv < l || !count) {
return 0;
}
if (l <= lv && rv <= r) {
return count;
}
extend();
return left->getCount(l, r) + right->getCount(l, r);
}
void add(long long newVal) {
count++;
sum += newVal;
if (lv < rv) {
extend();
(newVal <= left->rv ? left : right)->add(newVal);
}
}
void remove(long long newVal) {
count--;
sum -= newVal;
if (lv < rv) {
extend();
(newVal <= left->rv ? left : right)->remove(newVal);
}
}
};
node *newNode() {
static node buf[1111111];
static int bufSize = 0;
return &buf[bufSize++];
}
main() {
long long val;
node *r = newNode();
r->lv = 0;
r->rv = 1e18;
///add val
r->add(val);
///remove val
r->remove(val);
///sum of elements greater than val
r->getSum(val + 1, 1e18);
///count of elements greater than val
r->getCount(val + 1, 1e18);
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCgpzdHJ1Y3Qgbm9kZTsKbm9kZSAqbmV3Tm9kZSgpOwoKCnN0cnVjdCBub2RlIHsKCWxvbmcgbG9uZyBsdiwgcnYsIHN1bTsKCWludCBjb3VudDsKCW5vZGUgKmxlZnQsICpyaWdodDsKCW5vZGUoKSA6IGxlZnQoTlVMTCksIHJpZ2h0KE5VTEwpLCBjb3VudCgwKSwgc3VtKDApIHt9CgoKCXZvaWQgZXh0ZW5kKCkgewoJCWlmICghbGVmdCkgewoJCQlsb25nIGxvbmcgbSA9IChsdiArIHJ2KSAvIDI7CgkJCWxlZnQgPSBuZXdO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