As you know, the most intelligent beings on the Earth are, of course, cows. This conclusion was reached long ago by the Martian aliens, as well as a number of other intelligent civilizations from outer space.
Sometimes cows gather into cowavans. This seems to be seasonal. But at this time the cows become passive and react poorly to external stimuli. A cowavan is a perfect target for the Martian scientific saucer, it's time for large-scale abductions, or, as the Martians say, raids. Simply put, a cowavan is a set of cows in a row.
If we number all cows in the cowavan with positive integers from 1 to n, then we can formalize the popular model of abduction, known as the (a, b)-Cowavan Raid: first they steal a cow number a, then number a + b, then — number a + 2·b, and so on, until the number of an abducted cow exceeds n. During one raid the cows are not renumbered.
The aliens would be happy to place all the cows on board of their hospitable ship, but unfortunately, the amount of cargo space is very, very limited. The researchers, knowing the mass of each cow in the cowavan, made p scenarios of the (a, b)-raid. Now they want to identify the following thing for each scenario individually: what total mass of pure beef will get on board of the ship. All the scenarios are independent, in the process of performing the calculations the cows are not being stolen.
The first line contains the only positive integer n (1 ≤ n ≤ 3·105) — the number of cows in the cowavan.
The second number contains n positive integer wi, separated by spaces, where the i-th number describes the mass of the i-th cow in the cowavan (1 ≤ wi ≤ 109).
The third line contains the only positive integer p — the number of scenarios of (a, b)-raids (1 ≤ p ≤ 3·105).
Each following line contains integer parameters a and b of the corresponding scenario (1 ≤ a, b ≤ n).
Output
Print for each scenario of the (a, b)-raid the total mass of cows, that can be stolen using only this scenario.
Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is recommended to use the cin, cout streams of the %I64d specificator.
Examples
Input
3
1 2 3
2
1 1
1 2
Output
6
4
Input
4
2 3 5 7
3
1 3
2 3
2 2
Output
9
3
10
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are given n up to 3e5, weights w_i up to 1e9, and p up to 3e5 queries. Each query gives a and b (1 ≤ a, b ≤ n). The scenario: Starting at index a, then a+b, a+2b, ... while ≤ n. We need sum of weights of those positions.
So basically, we need to answer many queries of the form: sum_{k=0}^{ floor((n-a)/b) } w_{a + k*b}.
That's like arithmetic progression queries on a static array.
We need an efficient method. n and p up to 3e5, so we can't per query iterate over all steps if b is small (then many steps). If b is large, steps are few; worst-case b=1 leads to O(n) per query, too slow.
We need to precompute something based on sqrt decomposition on step b: For small b (<= sqrt(n)), we can precompute prefix sums for each possible small b? But there are up to sqrt(n) distinct b? Actually b can be up to n, but we can precompute for b up to B = sqrt(n) (like 550). For each b from 1 to B, we can compute an array sum_b where sum_b[i] = w_i + (i+b <= n? sum_b[i+b] : 0) or we can compute prefix sums in reverse? Actually easier: For each b, we want to answer queries (a,b) quickly. We can precompute an array f[b][i] for b <= B and i from 1..n, representing the sum of w_i, w_{i+b}, w_{i+2b}, ... up to n. Then query (a,b) with b <= B is f[b][a]. This f can be computed in O(n * sqrt(n)) time: For each b from 1 to B, we iterate i from n down to 1, set f[b][i] = w_i + (i+b <= n ? f[b][i+b] : 0). This is O(nB) ~ nsqrt(n) ~ 3e5550 ~ 165 million, which may be borderline but likely acceptable in C++ with optimization? Actually 3e5 * 550 = 165e6, each operation simple addition. Might be okay, but we need to store f. For b up to B, we need an array of size (B+1)(n+1) ~ 550 * 300k = 165 million integers, each 8 bytes if using long long, that would be ~1.32 GB, too much. So we need memory efficient.
Alternative: We can compute on the fly for each b <= B? But we have up to 3e5 queries, many with small b, we could precompute for each b <= B the sum for all starting positions and store them, but memory must be limited. However we can compress: For each b, we only need to store for each residue class modulo b? Because for a given b, the positions with same remainder modulo b form an arithmetic progression. For query (a,b) we want sum of indices ≡ a (mod b) and >= a. Actually the sum of all w_i where i ≡ a (mod b) and i ≥ a. So if we precompute for each b <= B, an array of size b (or n?) perhaps we can compute prefix sums per residue.
Idea: For each b (1..B), we can group indices by residue mod b. For each residue r (0..b-1), we can compute the sum of w at positions that are ≡ r (mod b). But we need sum from a specific start, not from the first index of that residue. However, if we compute an array that for each position i we store something like cumulative sum in reverse order per progression. But maybe we can use a technique: For each b, we compute an array sum_b of length n (or n+1) that holds the sum from i to end stepping by b. But as argued, memory heavy.
Alternative: Instead of storing for all i, we can store for each b, an array of size n but only for the relevant indices? But all indices are relevant. However we can note that for small b, the step is small, so the number of sequences is large, but we can compute answer per query quickly by iterating if b > B. That's typical sqrt decomposition: for b > B, we iterate directly over at most n/B steps because number of steps = floor((n-a)/b) + 1 ≤ n/b < n/B ≤ sqrt(n). So for b > B, we can just loop and sum using O(sqrt(n)) time per query. For b <= B, we need O(1) per query.
Now for b <= B, we need to answer quickly without O(n) memory per b. We need a compact representation.
One approach: For each b <= B, we can compute prefix sums over the sequence of positions sorted by index, but not per start: we can store an array of length n, where we store cumulative sums in reverse order for that b? That's exactly f[b][i] and would be large. But we can compress because for each b, we only need to answer for arbitrary a. However we can precompute for each b, an array of size n that holds the sum from i to the next in progression? Actually to answer query (a,b) in O(1), we need f[b][a] precomputed. So we need for each b <= B, an array of n+1 longs. That's memory heavy.
But note that B is sqrt(3e5) ≈ 548. So n*B = 1.65e8 entries. If each entry is 8 bytes (int64), that's ~1.32 GB, too high. Possibly we can use 4-byte int? But weights up to 1e9, and sum of up to n terms can be up to 3e5 * 1e9 = 3e14, which fits in 64-bit (less than 2^63), so we need 64-bit. So 8 bytes per entry is required. So 1.32 GB is too high for typical memory limits (usually 256-512 MB). So we need a more memory-efficient approach.
Idea: Instead of storing for all i for each b, we can compute answer for small b using precomputed prefix sums per residue in a compressed way: For each b, we can have an array of size n that stores the cumulative sum for the residue class but in forward order. For a given a, we need sum of w_{a + k*b} for k=0..K. That sum equals (prefix_sum_residue[last_index] - prefix_sum_residue[first_index - step?]) but careful.
Consider fixed b. For each residue r mod b, we have the list of positions i such that i ≡ r (mod b), in increasing order. For a specific a (which has residue r = a mod b), we want sum of weights at positions in that list that are >= a. So if we have an array of positions and prefix sums for that list, we can locate a via binary search in O(log n) per query. But we need O(1) per query ideally. Since b is small, the number of queries with that b may be many, but maybe O(log n) is acceptable? p up to 3e5, so O(p log n) is okay. However we also have queries with b > B that we handle in O(sqrt(n)) each, which is about 550 ops per query worst-case, total up to 1.65e8 which might be okay? Let's see: p up to 3e5, if all queries have b > B, each takes up to n/b ≤ sqrt(n) ≈ 550 steps, so worst-case 3e5 * 550 = 165e6 additions, which is similar to the precomputation complexity. That might be acceptable in C++ if optimized. But we also have queries with b ≤ B, which we could handle by direct iteration as well? If b is small, number of steps is large (up to n). For b=1, steps=n, so up to 3e5 queries * 3e5 = 9e10, impossible. So we need efficient for small b.
So we need a method for small b that is efficient. Options:
Precompute for each b ≤ B an array of length n but store in a more compact manner: Since b is small, we could compute on the fly for each query by using precomputed prefix sums per residue, and using O(1) retrieval after O(1) index calculation. Let's think.
We could precompute for each b ≤ B, an array pref_b of size n+1 (or maybe n+ b) that holds sum for indices i in progression: essentially pref_b[i] = w_i + pref_b[i+b] if i+b ≤ n else w_i. But this array is of size n for each b. However we can store only for indices from 1 to n, but that's still n per b. But maybe we can compress because we only need for starting positions a that are queried. However queries can be any a. But note that for a given b, the number of distinct residues is b, and for each residue, the number of positions is about n/b. We can store for each residue a vector of cumulative sums. For each b ≤ B, we can create b vectors: for r = 0 to b-1 (or 1 to b, but mod). For each position i such that i% b = r (or (i-1)%b? Actually indices start at 1. We'll treat r = (i mod b) maybe use 1-index mod). To handle quickly, we can map index a to its position in the vector for its residue. Then the sum from a to end of progression is simply suffix sum in that vector from that position to end. But suffix sum can be precomputed as prefix sums in reverse. So we can store for each b, for each residue r, a vector of the weights of positions in that residue in increasing order, and also a suffix sum array (or prefix sum from start, and then suffix = total - prefix before). Then for a given a, we need to find the index in the vector corresponding to a. Since positions are in increasing order, we can binary search to find the index. That's O(log (n/b)) per query, which is O(log n). With p=3e5, that is okay (3e5 * log(3e5) ≈ 3e5*19 = 5.7e6). But we also have to handle many b values. However for each query with b ≤ B, we do a binary search. That seems acceptable.
But we need to create these structures for all b ≤ B, total size: sum_{b=1}^{B} (b * (average size of vector)?? Actually each index i contributes to exactly one b for each b? Wait, for each b we are grouping indices by residue mod b. For each b, we store b vectors, each containing about n/b elements. So total number of stored elements across all b is sum_{b=1}^{B} (b * (n/b)) = sum_{b=1}^{B} n = B * n. That's exactly n * B, the same as before, but now each element is stored once? Actually yes, for each b, we have n entries across all vectors (since each index appears exactly once in one of the b residues). So total stored data is n * B entries. That's the same as before! But previously we stored f[b][i] array of size n for each b, which also had n * B entries. So memory is still n * B ~ 1.65e8 entries. However note that in the vector approach, each entry is just a weight (or sum). But we also need to store suffix sums maybe as separate array, but we can compute suffix on the fly if we store prefix sums. Actually to answer sum from a to end, we could store the vector of weights and also a suffix sum array (or prefix sums). However we can compute total sum for a residue and then subtract prefix up to before a. That would require prefix sums. Storing both weights and prefix sums would double memory. But we can just store prefix sums (cumulative from start) and then compute suffix = total - prefix_before. So we need one 64-bit value per element for each b. So again it's n*B 8-byte numbers. So still 1.3 GB.
So that's not better.
But maybe we can compress further by noticing that we don't need to store for all b up to B? Maybe we can choose B smaller to reduce memory, but then queries with b > B will be slower. We need to balance time and memory.
We could choose B such that nB fits memory, say 300 MB? 3e5 * B * 8 = memory. For memory 256MB, we have 2562^20 ≈ 268 million bytes. nB8 ≤ 268e6 => B ≤ 268e6 / (3e5 * 8) ≈ 268e6 / 2.4e6 ≈ 111.7. So B ≈ 100. Then sqrt(n)=548, so B=100 would make heavy queries for b>100: maximum steps = n/b, with b >100, n/b < 3000. So per query worst-case steps ~3000, total p up to 3e5 => 9e8 operations, maybe borderline but perhaps optimized C++ could handle? 9e8 additions might be too slow. We need to estimate. 9e8 operations might be ~2-3 seconds per 1e8? Usually 1e8 simple operations might be around 0.3-0.5 seconds in optimized C++? Actually it depends. 9e8 could be 4-5 seconds or more, possibly too slow. So we need B larger to reduce heavy query cost, but memory constraints prevent B large.
We could try a different approach: Use offline processing or Mo's algorithm? Or use direct formula with precomputed answers for all possible queries? That's p up to 3e5, but total unique (a,b) pairs? Could be up to p but we can compute each lazily.
Another direction: Use sqrt decomposition on both a and b? Or use "jump pointers" concept: for each position i, precompute sum for steps up to sqrt? Hmm.
We can precompute for all b up to B an array f[b] of size n, but store it as a 2D array of int64 with B rows. But memory is issue. Could we use short B, like B = 550, but compress by using a smaller data type? No, we need 64-bit. Could we compute f on the fly for each query? Not feasible.
Maybe we can treat queries offline and group by b, and for each b compute all queries with that b using a sweep. Since p up to 3e5, and b values up to n. For a given b, we can answer all queries (a,b) by iterating over the progression and using prefix sums? Actually we could for each b that appears in queries, precompute something only for that b. The number of distinct b values could be up to p, but in worst-case, p = 3e5, each query could have a different b, so we could have up to 3e5 distinct b values. Precomputing for each such b naively would be O(n * distinct_b) which is too large.
But we can handle queries differently: For each query, we can compute sum by iterating over indices if the step is large (b > B). For small step, we can use precomputation for b ≤ B. So we need precomputation for all small b up to B, but memory is issue. However maybe we can compress f[b] using that we only need to answer for queries with b ≤ B, and we can compute f[b] on the fly for each b but store it temporarily? We could process all small-b queries offline by grouping by b, and for each b we compute the necessary sums using a single pass over array of size n, and then answer all queries for that b, then discard the computed array. That way we don't need to store all b simultaneously, just one b at a time. Since b ≤ B, number of distinct b values among queries that are ≤ B could be up to B (at most B distinct values). Actually if B = sqrt(n) ≈ 548, then there are at most 548 distinct small b values. That's manageable. Even if queries have many different b, but they are limited to <= B, the distinct count cannot exceed B. So we can process each b separately. That solves memory issue! Because we can for each b from 1 to B, compute something like an array sum_b of length n (or just needed positions) and answer all queries with that b, then free it. But we would need to handle all queries, including those with b > B, which we do by direct iteration.
But careful: We have p up to 3e5. We'll need to store queries and group them by b. For each b ≤ B, we compute the array f_b[i] = sum from i to n stepping by b (or we can compute prefix sums per residue). Then for each query (a,b) we output f_b[a]. Then discard f_b.
The total time for precomputation for all b ≤ B: For each b, we compute f_b by iterating from n down to 1: f_b[i] = w_i + (i+b<=n ? f_b[i+b] : 0). That is O(n) per b, and there are B different b values, so total O(n * B) = O(n * sqrt(n)) ≈ 165e6 operations, which is acceptable. Memory for one f_b array is O(n) ~ 3e5 * 8 = 2.4 MB, very small. So that's perfect!
But wait: For each b, we need to answer queries for that b. However, queries with same b might have many a values. After we compute f_b, we can answer all those queries in O(1) each.
Now, queries with b > B we handle by direct iteration: for each such query, we loop k from a to n step b, sum w_i. The number of steps per query is at most n/b < n/B ≤ sqrt(n) ≈ 550. So worst-case operations for all such queries is p * sqrt(n) = 3e5 * 550 = 165e6, similar to precomputation. So total operations ~ 3e8? Actually precomputation ~165e6, plus heavy query sum ~165e6 = 330e6 operations, which might be okay in C++ if optimized (maybe borderline but likely fine). We can also further optimize: For b > B, we can also precompute something? But likely fine.
But careful: The direct iteration for each query is simple loop, but we need to access w_i. That's fine.
Thus solution:
Read n, w[1..n].
Read p, store queries. We'll need to answer queries in order? Output should correspond to input order. So we store queries with index.
Determine threshold B = floor(sqrt(n)). Usually sqrt(300000) ≈ 547.7, we can set B = 550 or 548. But we need to choose B such that n/B is small enough and B not too large to cause many precomputations. Let's compute more precisely: Let B = sqrt(n) ≈ 548. Precomputation for b=1..B: n * B = 3e5 * 548 = 164.4e6. Each iteration does a few operations, likely under 1 second? Actually 1.6e8 operations might take about 1-2 seconds in C++ if optimized, maybe a bit more. Adding 1.6e8 for heavy queries yields total 3.2e8 operations, maybe around 2-3 seconds? Might be okay if code efficient.
But we can also set B = 400, then n/B = 750, heavy steps 750 per query, p * 750 = 225e6; precomputation n400 = 120e6; total 345e6, similar. Actually we can try to minimize total expected operations. The worst-case scenario is when all queries are either small b or large b. But we have both types. The total runtime is about nB + p * (n/B). To balance, we could set B = sqrt(p) maybe? But we have n and p similar magnitude. Actually we want to minimize total: nB + p(n/B). derivative gives B optimal = sqrt(p). With p up to 3e5, sqrt(p) ≈ 548, same as sqrt(n) since n also 3e5. So B = sqrt(n) ~ sqrt(p) is optimal. So we go with B = sqrt(n) (or maybe sqrt(max(n,p)) ).
But we must also consider that precomputing for all b from 1 to B may be unnecessary if no queries have that b. But we don't know which b appear. However B is only ~550, so even if some b not used, we still compute them. That's okay: 550 * n = 1.6e8, still fine.
But we might reduce by only precomputing for b that actually appear in queries (among those ≤ B). Since B is small, number of distinct b ≤ B among queries is at most B. In worst-case, they could all appear, so it's the same. But maybe some b are not used, but we could skip them. However easier is to precompute for all b ≤ B, to avoid grouping overhead. But grouping overhead might be small anyway. Let's think: we have to answer queries in order, we could process as follows: store all queries; group by b; for each b ≤ B, compute f_b and answer queries; for b > B, we answer by iteration. However if we compute f_b for all b 1..B, we don't need grouping; we can just answer each query by checking if b <= B: if yes, use precomputed f_b[a]; else iterate. That is simpler. But we need to have precomputed f_b for all b 1..B. That's okay. Memory: we will hold f_b for all b simultaneously? If we compute them all upfront, that would be B arrays of size n, memory ~ 1.3 GB again. So we cannot hold all simultaneously. So we must compute them one by one, or at least not store all at once. But we could compute f_b on the fly when answering queries, but we need to know which b are used. So we need to group queries by b. That's more efficient memory-wise.
Thus we will:
Read all queries, store them in an array of struct { a, b, idx }.
Determine B = int(sqrt(n)) maybe plus a bit.
Create a vector for each b from 1 to n? That would be huge. Instead, we create a map or array of vectors for b <= B? But we only need to group queries with b <= B. For b > B, we will handle directly.
We can:
Create an array of vectors queries_by_b of size n+1? But n=3e5, that's okay memory wise: we can have an array of vectors of length n+1. Each vector will store query indices (or a, idx). That's O(p) total storage. But we need only for b up to n. That's fine: array of n+1 vectors, each empty initially, that's memory overhead of about (n+1)*sizeof(vector) which is about 8 bytes per vector? Actually vector object typically small (maybe 24 bytes). 3e5 * 24 = 7.2 MB, okay. But many will be empty. That's acceptable. Or we can use unordered_map for b> B? Actually we can just have two categories: small b and large b. We'll group small b queries (b <= B) into an array of vectors for b = 1..B. For large b, we don't need grouping, we can just answer them one by one after we process small b? But we need to output answers in original order. So we need to compute answers in some order and store in an array answers[0..p-1]. So we can first iterate over all queries, for each, if b <= B, push (a, idx) into bucket[b]; else, store them in a list of large queries.
Then:
For each b from 1 to B:
If bucket[b] is empty, skip.
Else compute f array for this b: we can compute an array sum of size n+2 (maybe 1-indexed). Compute from n down to 1: dp[i] = w[i] + (i+b <= n ? dp[i+b] : 0). This dp gives exactly the sum from i stepping by b.
Then for each query (a, idx) in bucket[b], answers[idx] = dp[a].
(We can discard dp after each b.)
Then process each large query (a, b, idx) individually:
ans = 0; for (int i = a; i <= n; i += b) ans += w[i];
store answer.
Complexities:
Precomputation total across b with non-empty bucket: at most B times O(n) but we may compute dp for b even if bucket empty? We can skip empty. But worst-case all b ≤ B appear, so we compute for each b from 1 to B. That's O(n*B) again. But we only compute once per b, not per query. That's fine.
For large queries, each takes O(n/b) ≤ n/B steps. So total steps for large queries ≤ p * (n/B). With B = sqrt(n) ≈ 548, worst-case 3e5 * 548 = 164e6 steps. Steps are simple additions and loop increments. That's okay.
Potential improvements: For large queries, we can also precompute prefix sums for whole array? That doesn't help because step is >1.
Thus overall algorithm is efficient.
But wait: The dp array computation for each b is O(n). If B = 550, that's 550 * 300k = 165e6 operations. Each operation is addition and conditional. That's acceptable. We need to ensure we don't exceed time. 165e6 operations might be near 1-2 seconds. Additional 165e6 for large queries adds to ~330e6, which might be near time limit if strict (common time limit 2 sec?). But we can possibly optimize.
We can reduce precomputation by only computing for b that appear in queries. If the queries are random, many b values may not appear. But worst-case they might all appear. But we can still accept.
We can also set B slightly larger to reduce large query cost, but then precomputation increases. Since both are linear in B, the total is nB + pn/B. Derivative gives optimum B = sqrt(p). Since p max 3e5, sqrt = 547. That's what we have. So optimal total ops ~ 2 * n * sqrt(p) = 2 * 3e5 * 547 ≈ 328e6. That's manageable with good C++ code (maybe using fast I/O, optimizing loops). But we need to be careful with overhead.
We could also use a technique for large queries: if b is very large, steps are few, but still we iterate. That's fine.
Potential memory for w array: 3e5 ints (maybe 4 bytes) but we need 64-bit for sums; we can store w as int (4 bytes) and cast to 64-bit when adding. That's fine.
Now, we must ensure that dp array for each b is computed correctly. But careful: For a given b, the sum from a is w[a] + w[a+b] + ... until > n. Using dp: for i from n down to 1: dp[i] = w[i] + (i+b <= n ? dp[i+b] : 0). Then dp[a] is sum. Yes.
But we need to be mindful of 1-indexing: indices from 1 to n.
We'll allocate dp as vector of size n+2 (maybe n+1). We'll fill from n down to 1. We'll need w array accessible.
Edge cases: a may be > n? Input says a,b between 1 and n, so a is within 1..n. So fine.
Now, for large queries: loops: for (int i = a; i <= n; i += b) ans += w[i]; That's fine.
Now, we must also consider that p can be 3e5, and we are grouping small b queries. We'll need an array bucket of size B+1 (since b can be up to n, but we only bucket b up to B). But b up to n; for b > B we don't bucket. So bucket array size B+1 (with index b). That's fine.
Implementation steps:
Read n.
Read w[1..n] (int array maybe vector).
Read p.
Create vector< pair<int, int> > queries; or struct with a,b,idx.
Also create bucket: vector<vector<pair<int,int>>> bucket(B+1). Each entry holds vector of (a, idx).
Also create vector<tuple<int,int,int>> large_queries; // a,b,idx
For each query i from 0 to p-1:
read a,b.
if b <= B:
bucket[b].push_back({a, i});
else:
large_queries.push_back({a,b,i});
Create answers array of long long size p.
For b from 1 to B:
if bucket[b].empty(): continue;
else:
// compute dp
vector dp(n+2, 0); // we only need indices 1..n, but we can allocate n+2 to avoid bounds.
// compute from n down to 1
for (int i = n; i >= 1; --i) {
dp[i] = w[i];
if (i + b <= n) dp[i] += dp[i+b];
}
// answer queries
for (auto &q : bucket[b]) {
int a = q.first;
int idx = q.second;
answers[idx] = dp[a];
}
// dp freed automatically
For large queries: for each (a,b,idx):
long long sum = 0;
for (int i = a; i <= n; i += b) sum += w[i];
answers[idx] = sum;
Output answers in order (i from 0 to p-1), each on new line.
Check examples.
Example1:
n=3, w=[1,2,3]
p=2
queries: (1,1) b=1 <= B (B= sqrt(3)=1? Actually sqrt(3)≈1.7 so B maybe 2? But let's compute B = sqrt(n) = floor(sqrt(3)) = 1. So B=1. b=1 <=1 -> bucket[1] contains (a=1, idx0). Compute dp: for b=1: dp[3]=3, dp[2]=2+3=5, dp[1]=1+5=6 -> answer 6. Next query (1,2) b=2 > B? B=1, so large, iterate i=1 then i=3? Actually b=2: i=1, i=3, i=5>3 stop => sum=1+3=4 -> correct.
Now, memory: bucket size B+1 ~ 548 vectors, each vector holds pairs (a, idx). Total pairs = number of small-b queries, at most p=3e5, each pair 8 bytes (two ints) plus overhead in vector, but overall O(p) memory ~ few MB. Large queries stored similarly. w array: 3e5 ints ~ 1.2 MB. dp array: 3e5 long longs ~ 2.4 MB. So total memory comfortable.
Now, time: Precomputation loops: for each b from 1..B that appears, we do a loop from n down to 1. But if we skip empty buckets, we still might have to compute dp for all b if all appear. That's 165e6 iterations. Each iteration: dp[i] = w[i] + (i+b <= n ? dp[i+b] : 0); we can implement without branch using conditional? We can do: if (i + b <= n) dp[i] = w[i] + dp[i+b]; else dp[i] = w[i]; That's fine. Might be fast.
We can micro-opt: we can predeclare dp as vector(n+1) and then fill backwards. For i from n down to 1, we compute dp[i] = w[i]; if (i+b <= n) dp[i] += dp[i+b]; Use pointer arithmetic to avoid bounds checks? Might be okay.
Large queries: For each query, loop from a to n step b. That's at most n/B steps; we can write a simple for loop.
Potential issue: p=3e5, B=548, worst-case large queries count maybe 3e5. So 3e5 * average steps? average steps for b > B is about (n/(2*B)) maybe? Actually b > B, min b = B+1, max b = n. Average steps if b uniformly distributed between B+1 and n? The average of n/b for b in [B+1, n] is roughly n * (1/(n-B) * integral? Not trivial, but worst-case if all b are just above B, steps ~ n/(B+1) ≈ n/B ≈ sqrt(n). So worst-case 165e6 steps. Each step: addition and array access. That's okay.
But we also have to consider that for each large query, we are doing a loop that increments i by b. The loop overhead might be small.
We need fast I/O. Use scanf/printf or ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); And use long long for sums.
Potential optimization: For large queries, we can also use precomputed prefix sums if b is huge? But not needed.
Now, set B properly. We can compute B = int(sqrt(n)) maybe. But note that if n is small, B may be too small, e.g., n=1, B=1. That's fine. For n up to 3e5, B = sqrt(300000) = 547.722... Use B = 548. Or maybe we can compute B = sqrt(n) + 1. Let's think about the worst-case for large queries: steps = n / (B+1) could be slightly less than sqrt(n). With B = 548, n=300000 => n/B ≈ 547. So that's okay.
But we also must ensure that for b > B we treat as large. However, what if b is exactly B? That's small. So threshold is inclusive for small: b <= B. So large: b > B.
Now, an alternative: we could set B = 700? Then precomputation n*700 = 210e6, large queries n/B ≈ 428, total p * 428 = 128e6, sum 338e6, similar. But memory for bucket size 700 is fine. However if we precompute for all b up to B, we would have to hold all dp simultaneously if we don't group. But we are grouping, so we compute per b. So we can set B to any value we want, but we need to consider total runtime. The theoretical optimum is B = sqrt(p) but p up to 3e5. But p might be smaller. However to be safe, we can compute B = sqrt(max(n,p)). Since n and p are both up to 3e5, we can set B = 548. Or we could compute B = 700? That would increase precomputation maybe, but still within ~210e6, which is okay. But to be safe, we should aim for the minimal total operations. However we can also dynamically set B based on n and p? But p is known after reading input. We could compute p and set B = sqrt(p) or sqrt(n). Since p can be up to 3e5 but could be smaller, if p is small, we don't need to precompute many b because there may be few queries? Actually precomputation is per b that appear, not all b. If p is small, we could also limit B to something else. But we can just set a fixed B, say 550. That should work for all cases.
But careful: If n is 300000, p is also 300000, B=550 yields ~330e6 operations. Time limit unknown, but typical 2 sec maybe borderline. However many solutions use this sqrt decomposition approach and pass.
We can try to reduce constant factors:
For precomputation, we can compute dp using a single loop: for (int i = n; i >= 1; i--) { dp[i] = w[i-1]; if (i+b <= n) dp[i] += dp[i+b]; } But we can also compute without dp array? Actually we need dp to answer queries quickly for that b. But we can answer queries as we compute dp if we know a values? We need to answer after dp is fully computed because dp[a] might depend on later indices. So we need dp.
But maybe we can compute for each b only the needed a values using a different approach: For each b, we can sort the queries by a descending and compute running sum? That could be more efficient if number of queries for that b is small. But in worst-case, each b could have many queries, but we are already doing O(n) per b. Possibly we could combine: For b <= B, we could handle queries by iterating from n downwards and when we reach an a that is needed, we capture current sum. However that still requires iterating over n for each b, same as dp. So it's similar.
But perhaps we can reduce precomputation by only computing dp for indices that are queried? However the dp recurrence may need intermediate indices if a is not the largest. But if we only need dp[a] for specific a, we could compute it by starting from a and summing manually, but that would be O(number of steps) which could be large for small b. That's not good.
Thus the O(n) per b is necessary.
We can also try to precompute for all b <= B simultaneously using a technique: For each i, we can add w[i] to dp[i] for all b? That's again n*B.
Given the constraints, 1.65e8 operations for precomputation is acceptable if coded well. But we have also 1.65e8 for large queries. Combined 3.3e8. Might be near limit but likely okay.
We can further reduce large query cost by also using precomputation for large b? Not needed.
We can also apply a small optimization: For large queries, we can compute sum using a loop that increments index and adds, but we can also use a while loop. The for loop is fine.
But we need to be careful about integer overflow: sums can be up to n * max(w) = 3e5 * 1e9 = 3e14, fits in 64-bit.
Now, implement.
Potential pitfalls:
Input reading: n, then n weights, then p, then p lines of a b. Use scanf.
Use 0-index or 1-index for w array. We'll use 0-index in code but store w[0..n-1]. However indexing for queries is 1-based. So we can convert a to 0-index when accessing w. That is, w[a-1] corresponds to cow number a. So we need to be consistent.
In dp computation, if we use 0-index, we can allocate dp of size n. dp[i] (0-index) corresponds to cow i+1. Then recurrence: for i from n-1 down to 0: if i + b < n (since i+b in 0-index means (i+1)+b?), careful: In original, index numbering: cow number j. b step is on numbers. If we use 0-index array w[0..n-1] for cows 1..n, then cow j corresponds to w[j-1]. When stepping by b, we go from number a to a+b, so from index a-1 to (a+b)-1 = a-1 + b. So step in 0-index is exactly b. So recurrence: For i from n-1 down to 0: dp[i] = w[i]; if i + b < n: dp[i] += dp[i+b]; This yields sum for starting at cow i+1. Then query with a: we need dp[a-1]. So we need to convert.
Thus we can implement 0-index to simplify loops.
In large query loop: for (int i = a-1; i < n; i += b) sum += w[i]; Yes.
Now, grouping: We'll bucket by b. For each b (1..B), bucket[b] stores pairs of (a-1, idx) maybe? We can store original a (1-index) and convert when using dp. Since dp is 0-index, we can compute ans = dp[a-1]. So we can store a as 1-index and convert later.
Better: store a0 = a-1 to avoid conversion each time.
We'll read a, b; if b <= B: bucket[b].push_back({a-1, idx}); else: large_queries.push_back({a-1, b, idx});
Then dp[i] computed as described. For each (a0, idx) in bucket[b]: ans[idx] = dp[a0];
Now, large queries: for (a0, b, idx): for (int i = a0; i < n; i += b) ans[idx] += w[i];
Now, output answers in order.
Now, we need to decide B. We'll compute B = int(sqrt(n)) + 1 maybe. Let's compute sqrt(300000) ~ 547.72, floor = 547, plus 1 = 548. So B = 548. Or we could compute B = 550 for simplicity. Let's compute B = (int) sqrt(n) + 1. That ensures B ~ sqrt(n)+1. Then n/B <= sqrt(n) roughly. For n=1, B=2 maybe, but that's fine.
Alternatively, we can set B = 700? But that increases precomputation if many b used. But since we only compute for b that appear, if B is larger but number of distinct b <= B, but worst-case all b from 1 to B could appear, so it's linear in B. To be safe, choose B = sqrt(300000) ≈ 548.
But what if p is much smaller than n? For example, n=300000, p=1. Then B = 548 is not optimal: we would compute dp for all b up to 548? Actually we only compute for b that appear. If the only query has b=1, we compute dp for b=1 only. That's O(n). So fine. If the only query has b=300000 (large), then we iterate steps: n/b = 1 step, so fine. So our approach adapts to actual queries because we only compute for b that have queries. So B being larger does not force us to compute for all b up to B. We compute only for b that appear and are <= B. So we could set B to a higher value, like 1000, without penalty if there are no queries for those b. However, if there are many small b queries, they will be in bucket only for b up to B. If B is larger, then more queries might be considered "small" and we would compute dp for those b. That could increase precomputation if there are many distinct b up to 1000. But p is up to 3e5, it's possible to have many distinct b in [1,1000]. In worst-case, we could have queries with all b from 1 to 1000. Then precomputation would be O(n * 1000) = 300e6, which is larger but still maybe okay? 300e6 + large queries (now large queries only b > 1000, steps per query ≤ n/1001 ≈ 300) gives ~ 300e6 + p*300 = 300e6 + 90e6 = 390e6. That's a bit more but still could be okay. However to be safe, we set B to around sqrt(n) ~ 550 to keep worst-case manageable.
But note that p may be up to 3e5, and we could have many distinct b in small range. So it's best to keep B moderate.
Thus we adopt B = sqrt(n) + 1. We'll compute as B = (int) sqrt(n) + 1.
Now, we need to be careful with integer sqrt: int B = sqrt(n) + 1e-9? Use (int)sqrt(n) but sqrt returns double. Could use int B = (int) sqrt((double) n) + 1; This ensures B >= sqrt(n). Actually we want threshold such that b > B considered large, and we want B to be roughly sqrt(n). Using +1 makes B slightly larger than sqrt(n), which reduces large query steps a bit but increases precomputation if many small b. It's fine.
Now, implementation details:
We'll use vector w(n); read via scanf.
We'll use vector ans(p);
We'll create bucket as vector<vector<pair<int, int>>> bucket(B+1); // bucket[b] for b in 1..B
We'll have a vector for large queries: struct Large { int a0; int b; int idx; }; store.
Read queries:
for i in 0..p-1:
int a, b; scanf("%d %d", &a, &b);
a--;
if (b <= B) {
bucket[b].push_back({a, i});
} else {
large_queries.push_back({a, b, i});
}
Then for b = 1 to B:
if bucket[b].empty() continue;
vector dp(n, 0); // size n
for (int i = n-1; i >= 0; i--) {
dp[i] = w[i];
int next = i + b;
if (next < n) dp[i] += dp[next];
}
for (auto &q : bucket[b]) {
ans[q.second] = dp[q.first];
}
Then for each large query:
long long sum = 0;
for (int i = q.a0; i < n; i += q.b) sum += w[i];
ans[q.idx] = sum;
Then output: for i in 0..p-1: printf("%lld\n", ans[i]); (or use cout with I64d? The problem says do not use %lld, but for printf in C++ it's %lld? Actually they say: "Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is recommended to use the cin, cout streams of the %I64d specificator." That's confusing; typical for GCC on Windows, %I64d; on Linux, %lld works. Usually Codeforces accepts both %lld and %I64d. To be safe, we can use cout with 64-bit. Or use printf("%I64d\n", ans[i]) if on Windows. We'll use cout with ios_base::sync_with_stdio(false); cin.tie(0); and then cout << ans[i] << "\n"; That should be fast enough.
But we need to be careful: Using cin for input might be slower for large input. Use scanf for faster reading. But mixing cin and cout with sync turned off might still be okay if we only use scanf and printf? Actually we can use scanf for input and printf for output. But if we turn off sync, mixing can cause issues? Better to stick with scanf/printf to be safe. But problem statement mentions cin/cout and %I64d. But we can use printf with %I64d on Codeforces (they support it). But to avoid confusion, I'll use printf and %lld? Many Codeforces solutions use %lld for long long. However the statement says not to use %lld? Actually it says: "Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is recommended to use the cin, cout streams of the %I64d specificator." Possibly it's an old note for some compilers. On modern Codeforces, %lld works. But to be safe, I'll use printf with %I64d.
Alternatively, use cout with ios_base::sync_with_stdio(false); cin.tie(0); and then read with cin, but cin reading 3e5 numbers might be okay with sync off. I think scanf is faster. I'll use scanf.
Thus:
#include
#include
#include
using namespace std;
int main() {
int n;
scanf("%d", &n);
vector w(n);
for (int i = 0; i < n; i++) {
scanf("%d", &w[i]);
}
int p;
scanf("%d", &p);
int B = (int) sqrt(n) + 1;
vector<vector<pair<int,int>>> bucket(B+1); // index b
vector<pair<int,int>> large_queries; // we need also b and idx. But we need a0, b, idx. So struct.
// Let's define struct for simplicity.
struct LargeQ { int a0; int b; int idx; };
vector large;
for (int i = 0; i < p; i++) {
int a, b;
scanf("%d %d", &a, &b);
a--;
if (b <= B) {
bucket[b].push_back({a, i});
} else {
large.push_back({a, b, i});
}
}
vector ans(p, 0);
// process small b
for (int b = 1; b <= B; b++) {
if (bucket[b].empty()) continue;
vector dp(n, 0);
for (int i = n-1; i >= 0; i--) {
dp[i] = w[i];
int nxt = i + b;
if (nxt < n) dp[i] += dp[nxt];
}
for (auto& q : bucket[b]) {
ans[q.second] = dp[q.first];
}
}
// process large b
for (auto& q : large) {
long long sum = 0;
for (int i = q.a0; i < n; i += q.b) {
sum += w[i];
}
ans[q.idx] = sum;
}
// output
for (int i = 0; i < p; i++) {
printf("%I64d\n", ans[i]);
}
return 0;
}
Let's test with examples.
Example1:
n=3, w=[1,2,3], sqrt(3)+1=1+1=2? Actually sqrt(3)=1.732, floor+1 = 2. So B=2. Queries: (1,1): a0=0,b=1<=2 -> bucket[1]={0,0}. (1,2): b=2<=2 -> bucket[2]={0,1}. Process b=1: dp[2]=3, dp[1]=2+3=5, dp[0]=1+5=6 -> ans[0]=6. b=2: dp[2]=3, dp[1]=2 (since 1+2=3 >= n? Actually i=1: nxt=3>=3? n=3, indices 0..2. i=1, nxt=3 out of range, so dp[1]=2; i=0: nxt=2<3, dp[0]=1+dp[2]=1+3=4 -> ans[1]=4. Output matches. Good.
Example2:
n=4, sqrt(4)=2, +1 =3, B=3. Queries: (1,3): b=3<=3 -> bucket[3]={0,0}. (2,3): b=3 -> bucket[3] also add (1,1)? Actually second query: (2,3): a0=1, idx1 -> bucket[3] push (1,1). (2,2): b=2<=3 -> bucket[2]={1,2}. Process b=3: dp[3]=7, dp[2]=5 (nxt=5>=4), dp[1]=3+dp[4?] Actually i=1: nxt=4? i+b=4? i=1 + 3 =4, but n=4, indices 0..3, so nxt=4 out of range, dp[1]=3; i=0: nxt=3, dp[0]=2+dp[3]=9. So ans[0]=dp[0]=9, ans[1]=dp[1]=3. b=2: dp[3]=7, dp[2]=5 (nxt=4 out), dp[1]=3+dp[3]=10, dp[0]=2+dp[2]=7? Actually dp[0]=2+dp[2]=2+5=7 but we don't need. For query a=2 (a0=1) ans[2]=dp[1]=10. Output matches.
So works.
Now, consider performance: For each small b we allocate a vector dp of size n. That could be heavy if we do many allocations (up to B times). But allocating a vector of size n (3e5) 500 times could cause overhead. However, we can reuse a single vector and reinitialize? But we need to compute dp for each b separately; we could allocate a single vector dp(n) and reuse, but we have to compute dp values for each b. That's fine: we can allocate once outside the loop and reuse, but each time we need to fill it. However careful: dp values for previous b are overwritten. That's okay. So we can allocate dp once and reuse for each b to avoid repeated allocations. But we need to ensure size is n. So:
vector dp(n);
for b=1..B:
if bucket[b].empty() continue;
// compute dp for this b
for (int i=n-1; i>=0; i--) {
dp[i] = w[i];
if (i+b < n) dp[i] += dp[i+b];
}
// answer queries
...
But we must be careful: The recurrence uses dp[i+b] which for current b must be computed already (since we go from high to low). So it's fine. And we overwrite dp entries for each new b. This saves allocation overhead. Good.
Now, for large queries we don't need dp.
Now, we might also consider the case where b is 0? Input says b>=1, so fine.
Now, what about memory for bucket: bucket is an array of vectors of size B+1. B+1 ~ 550. That's fine.
Now, large_queries: we store all large queries. That's at most p, each with three ints. Fine.
Now, I/O: reading 300k*2 ints ~ 600k ints, plus n ints, fine.
Now, overall time: precomputation loops: for each b, we do n iterations. But note that we may have many b values with non-empty bucket. In worst-case all b from 1 to B appear, that's B iterations. So total iterations = n * (number of distinct b ≤ B). That's at most n*B. So ~165e6.
Large queries: each query up to n/b steps. If we sum over all large queries, total steps = sum_{i=1}^{p_large} ceil((n - a_i)/b_i) + 1. Worst-case when all b_i = B+1, steps ≈ n/(B+1) each, p_large up to p = 3e5, so steps ≈ 3e5 * (300000/548) ≈ 3e5 * 547 ≈ 164e6. So total steps ~329e6.
329 million operations of addition and loop, which is acceptable in C++ within 2-3 seconds if optimized. But we also have the loops for precomputation which also involve condition and addition. So total maybe 500 million? Actually precomputation includes 165 million, plus 165 million large = 330 million. Each iteration does few operations. That's borderline but should pass with fast I/O and optimizations.
We could try to further reduce large queries cost by using also prefix sums for large b? Not needed.
Another idea: For large b, we could also use the same dp concept but only for those specific b values? But that would require storing dp per b, but we can't store for many b. However we can answer large queries directly, it's fine.
But maybe we can reduce precomputation cost by using a technique: For b small, instead of computing dp for all n, we could compute sums only for residues. Actually we can compute dp for each b by processing each residue class separately: For r from 0 to b-1, iterate indices i = r, i < n, i += b and compute suffix sums. That's also O(n) per b, same.
We can also compute dp in reverse order using one loop as described.
Now, possible micro-optimizations:
Use array for w (vector or plain C array) for faster access.
Use pointers: for dp computation, we can compute with two pointers? But compiler will optimize loops.
Use int for w and long long for sums. Use local variables.
For large queries, we can precompute prefix sums? Not helpful.
Perhaps we can also precompute for b > B using sqrt decomposition on a? Not needed.
Now, there is a nuance: In the precomputation loop for each b, we do:
for (int i = n-1; i >= 0; --i) {
dp[i] = w[i];
if (i + b < n) dp[i] += dp[i+b];
}
But note that when i + b < n, dp[i+b] is already computed because i decreasing. That's fine.
Now, for b that are small, we could also skip computing dp for all indices if we only need answers for specific a. But we need dp[a] for many a values, but we could compute on the fly for each a by walking the progression, but that would be O(steps) per query, which for small b can be large. So dp is better.
Now, an alternative approach: Use prefix sums for each b in a compressed way, but we already have the grouping method, which is fine.
Now, we must be careful about integer types: w[i] is int up to 1e9, sum up to 3e14, so long long.
Now, one more optimization: For large queries, if b is very close to n, steps are 1 or 2. That's fine.
Edge Cases:
a may be 1.
b may be 1.
n=1.
Now, test for n=1, w=[5], p=1, query (1,1). B = sqrt(1)+1 = 1+1=2. b=1<=2 => small. bucket[1] = {0,0}. Process b=1: dp[0]=5, ans=5.
Now, we need to ensure that for b <= B but bucket empty we skip, but we also have to handle if B is greater than n? B = sqrt(n)+1, so B could be > n. But b max is n, and if B > n, then all b are <= B? Actually b is between 1 and n inclusive. If B > n, then all queries are considered small, and we have bucket array of size B+1 which could be larger than n. But B = sqrt(n)+1, for n=1, sqrt(1)+1=2, so B=2 > n=1, that's okay. For n=1, B=2, we allocate bucket size 3, which is small. For n=2, B= sqrt(2)+1 ≈ 1+1=2, B=2 which equals n. For n=3, B= sqrt(3)+1 ≈ 1+1=2, B=2 < n. So B is usually <= n for n>2. But for n very small, B might exceed n. That's okay; we will still bucket all queries as small because b <= n <= B. Then we will compute dp for each b that appears. But note that dp computation for b might have step > n? Actually b can be up to n, but dp array length is n, and we access i+b. For b > n? b is at most n, i+b could be >= n, so condition i+b < n handles that. So fine.
Now, memory for bucket: we allocate bucket of size B+1, but B+1 might be up to sqrt(3e5)+1 ≈ 549, which is fine.
Now, we might also consider that for small n, B could be like 2, but that's fine.
Now, one more potential improvement: If for a given b, the number of queries is small, we could answer them by direct iteration instead of precomputing dp for entire n. For example, if b=500 (which is > B? Actually if B=548, b=500 is <= B and would be considered small; but if only one query with b=500, we could answer by iterating steps (n/500 ≈ 600) which is comparable to precomputation cost of 300k. So precomputing dp for b=500 would cost 300k operations but only one query; it's more efficient to answer directly if steps per query < n? Actually 300k vs 600, so direct iteration is much cheaper. So we could refine: For b <= B, we should decide whether to precompute dp or answer directly based on number of queries for that b. If the number of queries for a given b is small (say less than n / b?), then it's cheaper to answer each query by direct iteration. Since n / b is the average number of steps per query. So total cost of direct iteration for all queries with that b would be sum of steps ≈ (#queries) * (n/b). Precomputation cost is n. So if (#queries) * (n/b) < n, i.e., (#queries) < b, then direct iteration is cheaper. So we could treat small b with small #queries as "large" effectively. But this adds complexity. However given B is about 550, n=300k, n/B ≈ 550. So for b near B, n/b ≈ 550. If #queries for that b is 1, then direct iteration cost 550, precomputation cost 300k. So it's 550 vs 300k, definitely better to iterate. For b=1, n/b = 300k, if #queries=1, then direct iteration cost 300k, precomputation cost 300k, similar. If #queries=2, direct cost 600k, precomputation 300k, precomputation cheaper. So we can incorporate a heuristic: For each b <= B, if bucket[b].size() * (n / b) < n (or some threshold), then we answer queries by direct iteration instead of dp. This could reduce total work especially for b near B with few queries.
But is this necessary? Let's approximate worst-case total operations with the simple approach. It might be okay, but we can add this optimization to be safe. However it adds some code complexity but manageable.
Let's analyze worst-case for simple approach: For b close to B, say b=500, if all queries happen to have b=500 (i.e., p=300k, all b=500). Then our algorithm would: bucket[500] has 300k entries. We compute dp for b=500: O(n) = 300k operations. Then answer 300k queries O(1) each, total 300k+300k = 600k. That's trivial. But wait, what about the case where we have many distinct b near B, each with few queries? The worst-case precomputation would be O(n * B) regardless of #queries if we compute dp for each b that appears. But if many distinct b appear, say all b from 1 to B each have at least one query, then we compute dp for all B values, total O(nB). That's 165e6. That's fine. But if each of those b has only one query, we could instead answer those queries by direct iteration and avoid precomputation, reducing total work. Let's compute: For b from 1 to B, if each has one query, total direct iteration cost = sum_{b=1}^{B} ceil(n/b) ≈ n * H_B ≈ 300k * ln(550) ≈ 300k * 6.3 ≈ 1.9e6, which is far less than 165e6. So indeed, if the distribution is such that small b queries are sparse, we could save time by not precomputing for those b. So maybe we should incorporate this heuristic.
But is it possible in worst-case that we have 300k queries and they are all with distinct b ≤ B? That would be at most B distinct b, but p could be 300k, so many queries could share the same b. The worst-case for our simple method occurs when we have many distinct b ≤ B and each appears at least once, forcing precomputation for all those b, but also there could be many queries per b, but precomputation cost is independent of number of queries; it's fixed per b. The worst-case total precomputation is when we have all b from 1 to B present, which is B * n. That's 165e6. That's not huge. However, the case where each b appears only once gives total precomputation still 165e6 but could be avoided. But 165e6 is not huge; the direct iteration for those B queries would be about 1.9e6, so we could improve. But 165e6 is still acceptable. However, we need to also consider large queries cost which could also be 165e6, total 330e6. Adding another 165e6 might push to 500e6, which could be too high. But the scenario where we have all b from 1 to B each with at least one query is plausible: e.g., p = 300k, we could have queries with b=1..500, maybe each appears many times, but they all appear at least once. So we must precompute for all b from 1 to B that appear, even if some have only one query. But we could decide to not precompute for a b if the number of queries for that b is small enough that direct iteration total cost < n. That would reduce total work, especially for b near B. For b=500, n=300k, one query direct cost 600; precomputation cost 300k; it's beneficial to use direct iteration. For b=1, direct cost 300k, precomputation cost 300k; they are similar, but precomputation allows O(1) per additional query; if there is only one query, either is similar; we could still precompute for simplicity but we could also directly iterate. For b=2, n/b=150k; direct cost 150k vs precomputation 300k; direct cheaper for one query. For b=3, 100k vs 300k. So threshold: if (#queries) * (n/b) < n, then direct iteration cheaper. That is #queries < b. So if number of queries for a given b is less than b, answer by direct iteration; else precompute. This is a common optimization in sqrt decomposition.
Given B is small (550), implementing this heuristic is easy and could reduce runtime in many cases, and doesn't add much overhead. Let's adopt it.
So algorithm:
For each b from 1 to B:
if bucket[b].empty() continue;
let cnt = bucket[b].size();
if cnt < b:
// answer each query by direct iteration
for each (a0, idx) in bucket[b]:
long long sum = 0;
for (int i = a0; i < n; i += b) sum += w[i];
ans[idx] = sum;
else:
// precompute dp
vector dp(n);
for i from n-1 down to 0: dp[i] = w[i]; if (i+b<n) dp[i] += dp[i+b];
for each (a0, idx): ans[idx] = dp[a0];
But careful: For the else case, we need to compute dp, which is O(n). This is beneficial if we have many queries for that b. Since cnt >= b, then precomputation cost n, and total direct cost would be at least cnt * (n/b) >= b * (n/b) = n, so at least equal. So precomputation not worse.
Now, this optimization ensures that total precomputation cost is at most sum over b where cnt >= b of n. In worst case, for b=1, cnt must be >=1 to precompute; since any b with at least 1 query could be precomputed if we follow rule? For b=1, condition cnt < b means cnt < 1, i.e., cnt=0, but bucket not empty, so cnt>=1, so cnt >= b? Actually b=1, condition cnt < b is false (since cnt >=1), so we precompute. That's okay. For b=2, if cnt =1, then 1 < 2, so we direct iterate, avoiding precomputation. So we only precompute for b where there are at least b queries. Since b can be up to B (550), this means we only precompute for b that have many queries. In worst-case scenario, could we have all b from 1 to B each with exactly b queries? That would sum of b over b=1..B is B(B+1)/2 ≈ 150k, which is less than p=300k, possible. Then precomputation would be for all b (since each has cnt = b, so cnt >= b, precompute). So we would still precompute for all b, costing n*B = 165e6. But then total direct cost saved is sum_{b} (b * (n/b)) = n * B, same as precomputation. So no worse. But if some b have fewer than b queries, we save.
Thus this heuristic is beneficial.
Now, also we should consider that for b > B, we already answer by direct iteration. So large queries are always direct.
Now, we need to be careful about integer division: n/b maybe not integer but we use i <= n-1? Actually steps count is about ceil((n - a0)/b) + 1, but average is about n/b. The condition cnt * (n/b) < n is approximate; using integer arithmetic might be safe: if cnt * (n / b) < n, but n/b is floor. Better: if cnt * ( (n-1)/b + 1 )? For precise, we could compare cnt * ( (n-1)/b + 1 ) < n? But that's more complex. Simpler: estimate that each query takes at most ceil(n/b) steps. The worst-case for a query is when a=1, steps = ceil(n/b). So max steps per query = (n + b - 1)/b. So total worst-case direct cost for all queries with this b = cnt * ((n + b - 1)/b). If that is < n, we prefer direct. But using cnt * ((n + b - 1)/b) < n as condition is more accurate. However for large b, this is similar. We'll adopt this.
But to simplify, we can compute totalDirectCostEst = cnt * ((n + b - 1) / b). If totalDirectCostEst < n, then answer directly; else precompute. This is a bit more accurate. Since cnt and b are small, it's fine.
Now, what about when cnt is exactly b? Let's check: cnt = b, totalDirectCostEst = b * ceil(n/b). Is that >= n? Since ceil(n/b) >= n/b, so b * ceil(n/b) >= b * (n/b) = n. So totalDirectCostEst >= n. So precompute is not worse. If ceil(n/b) > n/b, then totalDirectCostEst > n, so precompute might be strictly better. So condition could be totalDirectCostEst <= n? But we can just use < n to prefer direct when strictly cheaper; when equal, either is fine. We'll use < n to go direct.
Thus final algorithm:
Read n, w.
Read p.
Compute B = sqrt(n) + 1.
Create bucket of size B+1 (vector of vectors of pair<int,int>). For each query i:
read a,b; a0=a-1;
if b <= B: bucket[b].push_back({a0, i});
else: large.push_back({a0,b,i});
ans vector.
Process small b:
For b = 1 to B:
if bucket[b].empty() continue;
int cnt = bucket[b].size();
int maxSteps = (n + b - 1) / b; // ceil(n/b)
if (1LL * cnt * maxSteps < n) {
// answer directly
for each query in bucket[b]:
long long sum = 0;
for (int i = q.first; i < n; i += b) sum += w[i];
ans[q.second] = sum;
} else {
// precompute dp
vector dp(n);
for (int i = n-1; i >= 0; --i) {
dp[i] = w[i];
if (i + b < n) dp[i] += dp[i+b];
}
for each query:
ans[q.second] = dp[q.first];
}
Process large:
for each q in large:
long long sum = 0;
for (int i = q.a0; i < n; i += q.b) sum += w[i];
ans[q.idx] = sum;
Print.
Now, we must ensure we reuse dp vector to avoid multiple allocations. In the else branch, we allocate dp vector each time; but we could allocate once outside and reuse, but careful: we need dp of size n; we can allocate dp outside the loop and use it. But we need to clear it? Actually we fill all entries during computation. So we can have a single vector dp(n) declared before the b loop, and within else branch we compute into it. But we must be careful that the dp array from previous b is overwritten, that's fine. However, if we use the same dp for multiple b, we need to ensure we don't read from dp before writing? In computation we rely on dp[i+b] which will be from current b's computation because we are filling from high to low. So it's fine to reuse. So we can declare dp once, and in else branch we compute using dp. But we also need to ensure that dp is sized n. We'll do:
vector dp(n);
for b=1..B:
if ... else:
// compute dp for this b
for (int i=n-1; i>=0; i--) {
dp[i] = w[i];
if (i+b < n) dp[i] += dp[i+b];
}
// answer queries using dp
That's fine. But note: In the direct answer branch, we are not using dp, so dp remains unchanged but that's okay.
Now, for small b with direct answer, we might also consider using a loop that increments i, summing w[i]. That's okay.
Now, about the condition: we compute maxSteps = (n + b - 1) / b; This is the maximum number of steps for a query (when a=1). However, queries can have a > 1, so actual steps may be less. So using maxSteps overestimates direct cost, making our condition more likely to choose direct? Actually we want to estimate worst-case direct cost to compare with precomputation cost n. If we overestimate, we might choose direct less often (since it seems larger), but we want to choose direct only when it's cheaper. Overestimating could cause us to not choose direct when it actually would be cheaper, but still precompute which is not worse? Actually if we overestimate, we might think direct cost is larger than it really is, making us precompute even when direct might be cheaper. That could lead to worse performance. But using maxSteps is safe in the sense that we are guaranteeing that direct cost is at most cnt * maxSteps; actual cost ≤ that. So if cnt * maxSteps < n, then actual direct cost is definitely < n, so direct is cheaper. If cnt * maxSteps >= n, actual direct cost could still be < n if many queries have large a? Possibly, but unlikely extreme. To be more accurate, we could compute the expected or average, but it's complicated. Using maxSteps is a simple heuristic that works reasonably. It may cause some suboptimal decisions but not many. Since B is small, it's fine.
Alternatively, we could compute for each query its step count exactly and sum them, but that would require iterating over queries anyway, defeating the purpose. So we'll stick with this.
Now, total complexity: In worst-case, we might still precompute for many b, but that's fine.
Now, we need to handle the possibility that B could be larger than n? If n is small, say n=1, B = sqrt(1)+1=2, b up to 1. For b=1, bucket[1] has queries. cnt maybe 1. maxSteps = (1+1-1)/1 = 1. cnt*maxSteps = 1 < n? n=1, so 1 < 1 false, so precompute? Actually 1 < 1 false, so we go to else branch (precompute). Precomputation cost n=1, trivial. Direct also cost 1, either is fine.
Now, final code.
Potential improvements: Use fast reading and writing.
Implementation notes:
Use scanf for ints.
Use printf for output with "%I64d". Or use cout with ios::sync_with_stdio(false) and then cout << ans[i] << "\n". But mixing scanf and cout with sync off may cause issues if not careful. Since we use scanf for input, we should use printf for output to avoid mixing. But if we turn off sync, we can mix but it's not recommended. So we'll use printf.
For long long, we need to use %I64d on Windows, but on Codeforces it's accepted. Alternatively, we can use long long and %lld, but statement warns. I'll use %I64d.
Now, test with examples.
Now, consider edge case: n=300000, p=300000, all queries with b = 1 (small). Then bucket[1] size = 300000. B ~ 548, b=1 <= B. cnt = 300k, maxSteps = n. cnt*maxSteps = 300k * 300k = 9e10, >> n, so precompute. We compute dp for b=1 once (300k ops). Then answer each query O(1). So total ~300k + 300k = 600k operations, plus overhead for grouping. Good.
If all queries with b = 500 (small), cnt=300k, maxSteps = ceil(300000/500)=600. cnt*maxSteps= 180e6 > n=300k, so precompute. Precomputation cost 300k, answer cost 300k, total 600k. Good.
If all queries with b = 600 (large), they go to large. Then each query steps = ceil(300000/600)=500. So total steps = 300k * 500 = 150e6. That's acceptable.
If half queries are small with b=2 and cnt=150k, then b=2 <= B, cnt=150k, maxSteps=150k, cnt*maxSteps= 2.25e10 > n, so precompute. Precomputation cost 300k. Then answer 150k O(1). Good.
Worst-case for precomputation: we have queries for all b from 1 to B, each with cnt >= b (so we precompute for all). That's 550 * 300k = 165e6. Plus answer queries (which may be up to p=300k) O(1) each, negligible. Plus large queries none. So total 165e6.
Large queries worst-case: all queries have b = B+1 = 549, steps ~ 547. So total steps ~ 300k * 547 = 164e6.
Combined worst-case: if we have 300k queries, half of them are small requiring precomputation? But precomputation cost is per b, not per query. If we have many distinct b, we pay n per b. But the maximum number of distinct b ≤ B is B, so precomputation cost capped at nB regardless of number of queries. So combined worst-case could be nB (precompute) + p*(n/B) (large). But can both occur simultaneously? If we have queries for all b from 1 to B (so precompute all) and also many queries for b > B, that would exceed p? p is fixed at 300k. If we have both types, the sum of queries is p. So precomputation cost is independent of number of small queries, but large queries cost depends on number of large queries. In worst-case we could have p large queries and also small b queries? That would exceed p because total queries is p. So if we have many small b queries, large queries count reduces. So overall total operations ≤ max(nB, p(n/B)) + something? Actually worst-case total operations could be nB + p(n/B) if we have both small and large queries such that small ones cause precomputation for all B and large ones are many. But note that if we have large queries, we are not using precomputation for those b, but we could have precomputation for many small b and also many large queries, but then total queries = (#small) + (#large) = p. In worst-case, we could have #small = something and #large = p - #small. But to maximize total operations, we want both precomputation (nB) and large steps (p_large * n/B) to be high. Precomputation is fixed at nB if all B small b appear. That's ~165e6. Then if we also have p_large large queries, maximum p_large can be p - (minimum number of small queries that cause all B to appear). To cause all B to appear, we need at least one query for each b from 1 to B. So minimum small queries = B (e.g., one per b). So maximum large queries = p - B ≈ 300k - 550 ≈ 299450. Then large steps cost ≈ 299450 * n/B ≈ 299450 * 547 ≈ 163.8e6. So total ≈ 329e6. That's the same as earlier bound. So overall worst-case ~330e6 operations. That's acceptable with optimizations.
Now, with the heuristic, if we have many b with cnt < b, we avoid precomputation and instead answer directly. For b near B, direct cost per query is about n/b ≈ 547, and if cnt = 1, direct cost = 547, precomputation cost = 300k, so we save. In the scenario where we have all b from 1 to B each with one query (small queries = B), then without heuristic we would precompute all B (165e6) and answer B queries (B). With heuristic, we would direct iterate for b where cnt < b. For b=1: cnt=1, b=1, cnt >= b? 1 >= 1, so still precompute? Actually condition cnt < b: 1 < 1 false, so we precompute b=1. For b=2: cnt=1 < 2, direct. For b=3: cnt=1 < 3, direct. ... up to b=550: cnt=1 < 550, direct. So only b=1 is precomputed (cost 300k). For b=2..B direct: each direct cost ~ n/b. Total direct cost = sum_{b=2}^{B} ceil(n/b). For n=300k, B=550, sum_{b=2}^{550} ≈ n * (H_550 - 1) ≈ 300k * (6.3 - 1) = 300k * 5.3 = 1.59e6. So total ~ 300k + 1.59e6 = 1.89e6. That's a huge reduction from 165e6. So heuristic is beneficial for such distribution.
But what about the worst-case we considered earlier with precomputation for all b? That required each b to have cnt >= b. So if we have 300k queries, to have all b with cnt >= b, we need at least total queries sum_{b=1}^{B} b = B(B+1)/2 ≈ 150k, which is possible. Then precomputation still occurs for all b, costing 165e6. But that's necessary because total direct cost would be at least that. So overall, our heuristic yields near-optimal total work.
Thus we include heuristic.
Now, we need to compute maxSteps = (n + b - 1) / b. Since n and b are ints.
Now, regarding dp computation: When we compute dp in else branch, we need to use dp vector. But careful: In the direct answer branch, we also need to compute sum by iterating. That's fine.
Now, we also need to consider that w is int; when we sum into long long, we should cast.
Now, large queries: we already iterate.
Now, we should test with examples.
Let's simulate quickly.
Example1: n=3, w=[1,2,3], B= sqrt(3)+1 = 1+1=2.
bucket[1]: cnt=1, maxSteps = (3+1-1)/1 = 3, cntmaxSteps = 3, n=3 => not < n (3<3 false) => precompute. bucket[2]: cnt=1, maxSteps = (3+2-1)/2 = (4)/2=2, cntmaxSteps=2, n=3 => 2<3 true => direct. So for b=2, we direct iterate. Works.
Example2: n=4, B= sqrt(4)+1 =2+1=3.
bucket[3] has cnt=2, maxSteps = (4+3-1)/3 = (6)/3=2, cntmaxSteps=4, n=4 => not < 4? 4<4 false => precompute. So precompute for b=3. bucket[2] cnt=1, maxSteps = (4+2-1)/2 = (5)/2=2? Actually (4+2-1)=5/2=2 (integer division) =2, cntmaxSteps=2, n=4 => 2<4 true => direct. So for b=2 direct. Works.
Now, we should also test scenario where b=1, cnt=1: n=5, B= sqrt(5)+1=2+1=3? sqrt(5)=2.236, floor=2, +1=3. b=1, cnt=1, maxSteps=5, cnt*maxSteps=5, n=5 => not <5, so precompute. That's fine.
Now, one more scenario: b=400, n=300000, cnt=1, maxSteps = (300000+400-1)/400 = (300399)/400 = 750? Actually 300399/400=750.9975, floor 750? Wait ceil: (n+b-1)/b = (300000+399)/400 = 300399/400 = 750.9975, integer division truncates to 750? But we need ceil. (300000+400-1)=300399, /400 = 750 with remainder 399? Actually 400750=300000, so (300000+400-1)=300399, 400750=300000, remainder 399, so integer division gives 750, but we need ceil, which is 751 because n=300000, b=400, ceil(300000/400)=750? Wait 300000/400 = 750 exactly because 400750=300000. So steps for a=1: i = 1, 401, 801,... up to 300001? Actually if n=300000, then the last term is 300000 if (300000-1)%400 ==? Let's compute: indices: 1, 401, 801, ... up to <=300000. The largest multiple: 1 + k400 <= 300000 => k <= (299999)/400 = 749.9975, so k=749, then index = 1+749400=1+299600=299601. That's not 300000. Actually wait, we start at a=1. So the sequence includes 1, 401, 801,... The maximum index <= 300000. For b=400, the numbers are 1 mod 400. 300000 mod 400 = 0? Actually 400750=300000, so 300000 ≡ 0 mod 400, not 1. So it's not included. So the number of terms is floor((300000-1)/400)+1 = floor(299999/400)+1 = 749+1=750. So ceil(300000/400)=750? 300000/400=750. So yes steps=750. So maxSteps = 750. So (n+b-1)/b = (300000+399)/400 = 300399/400 = 750 (since 400750=300000, remainder 399, but integer division gives 750 because it truncates). Actually 300399/400 = 750.9975, integer division truncates to 750, but we want 751? That would be wrong. Let's compute correctly: ceil(n/b) = (n + b - 1) / b using integer division (floor). For positive ints, this formula works because (n + b -1) // b = floor((n+b-1)/b). For example, n=10, b=3: ceil(10/3)=4, (10+3-1)=12/3=4 correct. For n=300000, b=400: n+b-1=300000+399=300399, 300399/400=750? 400750=300000, remainder 399, so integer division yields 750, but we need 750? Actually ceil(300000/400)=750, because 300000/400 = 750 exactly. So formula should give 750. But we computed 300399/400 = 750? 300399/400 = 750.9975, integer division truncates to 750, giving 750. That's correct. So (n+b-1)/b gives 750, which is correct. So no issue.
But earlier we thought ceil division might give 751, but it's fine.
Now, check b=1: (n+1-1)/1 = n, correct.
Now, with cnt=1, totalDirectCostEst = 1 * 750 = 750, n=300000, so direct cheaper. Good.
Now, for b=2, maxSteps = ceil(300000/2)=150000, cnt=1, totalDirectCostEst=150000, n=300000, still direct cheaper. So our condition will direct for b=2 with one query.
Now, if cnt=2 for b=2, totalDirectCostEst=300000, not < n, so precompute. That's fine.
Now, implement.
Now, possible edge: For b <= B but bucket empty we skip.
Now, ensure we use 64-bit for multiplication in condition: 1LL * cnt * maxSteps.
Now, we need to handle large queries similarly? No need.
Now, about reading: We'll use scanf.
Now, about output: Use printf with "%I64d". Could also use cout with long long and <<.
Now, finalize.
Potential micro-optimizations:
For direct iteration, we can use a while loop: i = a0; while (i < n) { sum += w[i]; i += b; }
For dp computation, we can use pointer arithmetic: long long* dp_ptr = dp.data(); int* w_ptr = w.data(); but not necessary.
We can precompute w as vector but use .data() for speed.
We can also consider using register but compiler optimizes.
Now, let's think about memory for dp: vector dp(n). That's about 2.4 MB. Good.
Now, what about the bucket vectors: each bucket holds pairs of ints. Using vector<pair<int,int>>. That's fine.
Now, we should ensure we reserve enough capacity? Not needed.
Now, time complexity should be fine.
Now, let's implement.
Now, test with random small cases vs brute force to ensure correctness.
We'll do mental test: n=5, w = [1,2,3,4,5]. p random.
But trust.
Now, potential bug: In dp computation, we need to ensure that we compute for all i from n-1 down to 0. For i such that i+b >= n, we skip addition. Works.
Now, for direct iteration, we start at a0 (0-index) and add while i < n. That includes a0.
Now, one more nuance: When we precompute dp for a given b, we compute dp[i] as sum from i stepping by b. That includes w[i] and all later ones. That's correct for query (a,b). For a that is not congruent to the starting residue? Actually query a is any number, dp[a-1] gives sum from that index. Works.
Now, ensure that we treat a0 correctly.
Now, code.
Now, we may also consider if B computed as sqrt(n) + 1 might be less than 1? n>=1, sqrt>=1, +1 => at least 2. So B>=2. That's fine.
Now, we could also set B = 550 constant to avoid sqrt computation, but we'll compute for clarity.
Now, let's write final solution.
Potential improvement: Since we are grouping by b, we might also want to sort bucket[b] to perhaps improve cache? Not needed.
Now, let's code.
Implementation details:
code
#include <cstdio>
#include <vector>
#include <cmath>
using namespace std;
int main() {
int n;
scanf("%d", &n);
vector<int> w(n);
for (int i = 0; i < n; ++i) {
scanf("%d", &w[i]);
}
int p;
scanf("%d", &p);
int B = (int) sqrt(n) + 1;
vector<vector<pair<int, int>>> bucket(B+1);
struct LargeQ { int a0; int b; int idx; };
vector<LargeQ> large;
for (int i = 0; i < p; ++i) {
int a, b;
scanf("%d %d", &a, &b);
--a;
if (b <= B) {
bucket[b].push_back({a, i});
} else {
large.push_back({a, b, i});
}
}
vector<long long> ans(p, 0);
vector<long long> dp(n); // reusable
for (int b = 1; b <= B; ++b) {
if (bucket[b].empty()) continue;
int cnt = (int) bucket[b].size();
int maxSteps = (n + b - 1) / b; // ceil(n/b)
if (1LL * cnt * maxSteps < n) {
// answer directly
for (auto& q : bucket[b]) {
int a0 = q.first;
long long sum = 0;
for (int i = a0; i < n; i += b) {
sum += w[i];
}
ans[q.second] = sum;
}
} else {
// precompute dp for this b
// compute from end
for (int i = n-1; i >= 0; --i) {
dp[i] = w[i];
if (i + b < n) {
dp[i] += dp[i + b];
}
}
for (auto& q : bucket[b]) {
ans[q.second] = dp[q.first];
}
}
}
// large b
for (auto& q : large) {
long long sum = 0;
for (int i = q.a0; i < n; i += q.b) {
sum += w[i];
}
ans[q.idx] = sum;
}
// output
for (int i = 0; i < p; ++i) {
printf("%I64d\n", ans[i]);
}
return 0;
}
Let's test with given examples.
Example1:
Input:
3
1 2 3
2
1 1
1 2
n=3, B = sqrt(3)+1 = 1+1=2.
bucket: b=1: (a0=0, idx0); b=2: (a0=0, idx1). large empty.
Now, consider test where b is large: e.g., n=10, p=1, query (2,10). B = sqrt(10)+1 = 3+1=4. b=10 > B, so large. Direct: a0=1, i=1 -> sum=w[1]; i=11 out. correct.
Now, test where b small but cnt<b: n=100, b=50, cnt=1. B ~10+1=11? sqrt(100)=10, +1=11, b=50 > B? Actually 50 > 11, so it's large, not small. So small b are only up to B=11. So b=50 goes to large, direct steps=2. That's fine. So the heuristic for small b only.
Now, ensure B is not too high such that b <= B includes many b. With n=300k, B=548, that's fine.
Now, one more nuance: In the dp precomputation, we use dp vector which is size n. But when we compute dp for a new b, we need to overwrite all entries. Our loop from n-1 down to 0 writes each dp[i]. That's fine. However, we rely on dp[i+b] which we have just computed for higher i. So it's correct. But note that dp vector might contain old values from previous b for indices > n? Not used. But after we compute for b=1, dp contains values. Then for b=2, we recompute from n-1 downwards; at each i, we read dp[i+b] which may have been overwritten already if i+b is less than n and we have already computed dp[i+b] in this same pass (since i decreases, i+b > i, so i+b is larger index; since we are going from high to low, i+b is already computed in this pass because i+b > i, and we have processed higher indices earlier. So it's safe. The old values from previous b are not used because we overwrite dp[i+b] before reading it. Good.
Now, but what about for indices near the end where i+b may be out of range? We don't read then.
Thus reuse works.
Now, also note that in the direct answer branch, we are not using dp, so dp remains unchanged but that's fine.
Now, about memory for large queries: we store a0, b, idx. That's okay.
Now, output: Use printf("%I64d\n", ans[i]). On some judges, they may want %lld. To be safe, we can use #ifdef or just use cout with ios_base::sync_with_stdio(false); cin.tie(0); and then cout << ans[i] << "\n"; With sync off, cout is fast. But we used scanf for input; mixing may cause issues if we don't turn off sync? Actually if we turn off sync, we can mix, but it's generally not recommended because the order may get messed if we don't flush. But if we do:
ios_base::sync_with_stdio(false);
cin.tie(0);
Then using scanf and cout together? The sync_with_stdio(false) disables synchronization between C++ streams and C stdio, meaning that mixing cin/cout with scanf/printf can lead to interleaving issues if not flushed properly. However, if we use only scanf for input and only cout for output, it might be okay if we don't use cin. But still it's risky. Better to stick with one style. Since we already use scanf for input, we can use printf for output. So we keep printf.
Now, but the problem statement says "do not use the %lld specificator ... recommended to use the cin, cout streams of the %I64d specificator." That's weird. Possibly they want us to use cin/cout with %I64d? Actually in C++, you cannot use format specifiers with cin/cout. They probably mean for printf/scanf, use %I64d. But they say "use the cin, cout streams of the %I64d specificator." That might be a translation error. Usually on Codeforces, for C++ they accept %lld and %I64d. Many solutions use %I64d in printf. So we'll use %I64d.
Now, ensure we include cmath for sqrt.
Now, final code as above.
Let's think about potential integer overflow in condition: cnt * maxSteps may exceed 2^31. Use long long.
Now, about time: The loops are straightforward. Might pass.
Now, could we further optimize direct iteration for small b? Not needed.
Now, test with n=300000, p=300000, all b=1 (small). Our algorithm: bucket[1] size = 300k, cnt=300k, maxSteps=n=300k, cnt*maxSteps huge, so precompute dp for b=1 (cost n). Then answer all queries O(1). So total about 300k operations for dp + 300k for answers = 600k. Very fast.
Now, worst-case as earlier: all b from 1 to B appear with at least b queries each (so total small queries sum >= B(B+1)/2, which could be up to 150k) and also many large queries for b > B (up to 300k - that). But if we have 150k small queries, we also have 150k large queries? Actually p=300k. So if small queries count = 150k, large = 150k. Then precomputation cost = n*B = 165e6. Large cost = 150k * (n/B) ≈ 150k * 547 = 82e6. Total ~247e6. Good.
If small queries count = 300k (all small), then large=0. Precomputation cost could be up to nB if many distinct b; but if all small queries are concentrated in few b, precomputation cost is low. Worst-case for precomputation is when we have many distinct b, but if all queries are small, the number of distinct b cannot exceed B. So precomputation cost is at most nB. So overall still within bound.
Thus total operations < 350e6.
Now, let's consider time: 350e6 integer additions and array accesses. In C++ on a 2GHz CPU, roughly 0.5 ns per operation? Actually typical 3-4 cycles per operation, maybe 1-2e8 operations per second? So 350e6 could be 1.5-2 seconds. Should be okay under 2 seconds? Might be close. But with optimizations (O2), it should be fine.
We can also micro-opt: In dp computation loop, we can use a more efficient pattern: for (int i = n - b - 1; i >= 0; --i) dp[i] = w[i] + dp[i+b]; then handle the tail separately. But not needed.
We can also use register variables.
I think it's fine.
Now, note: The problem originally may be from Codeforces. I recall a problem "Cowavans" or something like that. Many solutions use sqrt decomposition.
Now, final answer: Provide the code with explanation.
But we must produce final answer: the solution description and code.
I will now produce the final answer. ```cpp
#include
#include
#include
using namespace std;
int main() {
int n;
scanf("%d", &n);
vector w(n);
for (int i = 0; i < n; ++i) {
scanf("%d", &w[i]);
}
code
int p;
scanf("%d", &p);
int B = (int) sqrt(n) + 1; // threshold for sqrt decomposition
// group queries with small b (b <= B)
vector<vector<pair<int, int>>> bucket(B + 1);
struct LargeQ { int a0, b, idx; };
vector<LargeQ> large;
for (int i = 0; i < p; ++i) {
int a, b;
scanf("%d %d", &a, &b);
--a; // switch to 0‑based index
if (b <= B) {
bucket[b].push_back({a, i});
} else {
large.push_back({a, b, i});
}
}
vector<long long> ans(p, 0);
vector<long long> dp(n); // reusable array for precomputation
// process all small b
for (int b = 1; b <= B; ++b) {
if (bucket[b].empty()) continue;
int cnt = (int) bucket[b].size();
int maxSteps = (n + b - 1) / b; // ceil(n / b)
// if answering directly is cheaper than precomputing
if (1LL * cnt * maxSteps < n) {
for (auto& q : bucket[b]) {
long long sum = 0;
for (int i = q.first; i < n; i += b) {
sum += w[i];
}
ans[q.second] = sum;
}
} else {
// precompute dp[i] = sum of w[i], w[i+b], w[i+2b], ...
for (int i = n - 1; i >= 0; --i) {
dp[i] = w[i];
if (i + b < n) {
dp[i] += dp[i + b];
}
}
for (auto& q : bucket[b]) {
ans[q.second] = dp[q.first];
}
}
}
// process large b (b > B)
for (auto& q : large) {
long long sum = 0;
for (int i = q.a0; i < n; i += q.b) {
sum += w[i];
}
ans[q.idx] = sum;
}
// output
for (int i = 0; i < p; ++i) {
printf("%I64d\n", ans[i]);
}
return 0;