structBinaryIndexedTree { LL c[MAX_N]; int maxPos; BinaryIndexedTree() {} BinaryIndexedTree(int maxPos) { this->maxPos = maxPos; for (int i = 0; i <= maxPos; ++i) c[i] = 0; }
inlineintlowbit(constint &u){ return u & (-u); }
voidadd(int pos, int k){ while (pos <= maxPos) { c[pos] += k; pos += lowbit(pos); } }
LL sum(int pos){ LL ret = 0; while (pos >= 1) { ret += c[pos]; pos -= lowbit(pos); } return ret; } };
classMKAverage { public: BinaryIndexedTree cnt, sum; int node_tot, m, k; queue<int> q; MKAverage(int m_, int k_) { cnt = BinaryIndexedTree(1E5); sum = BinaryIndexedTree(1E5); node_tot = 0; m = m_; k = k_; } voidaddElement(int num){ cnt.add(num, 1); sum.add(num, num); q.push(num); ++node_tot;
if (node_tot > m) { auto f = q.front(); q.pop(); cnt.add(f, -1); sum.add(f, -f); --node_tot; } } // 第 p 个元素在 BIT 中的 index intpre_index(int p){ int l = 1, r = 1E5; while (l < r) { int mid = (l + r) >> 1; if (cnt.sum(mid) < p) { l = mid + 1; } else { r = mid; } } return l; } intcalculateMKAverage(){ if (node_tot < m) { return-1; } int l = pre_index(k); int r = pre_index(node_tot - k); if (l == r) { return l; } LL ans = sum.sum(r - 1) - sum.sum(l); ans += 1LL * l * (cnt.sum(l) - k); ans += 1LL * r * (node_tot - k - cnt.sum(r - 1)); ans = (ans / (node_tot - 2 * k)); return ans; } };