Official Solution

This uses merge-sort tree.

Time Complexity: O(NlogN+Qlog2N)O(N\log N+Q\log^2N)

Memory Complexity: O(NlogN)O(N\log N)

Alternative solution (Wavelet Tree)

Similar as K-query from SPOJ, but you additionally need to store prefix sums of AA.

Time Complexity: O((N+Q)logM)O((N+Q)\log M), where MM is the max value

Memory Complexity: O(NlogM)O(N\log M)

#include <bits/stdc++.h>
using namespace std;
struct PrefixSummer {
const int BITS = 64;
vector<uint64_t> packed;
vector<int> psums;
vector<int64_t> psumA;
void init(const vector<bool> &v, vector<int> A) {
packed.resize(size(v) / BITS + 1);

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!