Four contest problems rated 1,300 that count inside a band or answer many ranges. The move: turn a band into two 'at most' counts and subtract, and answer each range from a prefix table.
This tent holds four problems rated 1,300. Three of them count something inside a band from low to high, and one answers many range questions. None of them needs a new data structure, only the right way to turn the question into passes.
| Problem | The question | Turned into |
|---|---|---|
| Feature flags after deploys | the flags on after the deploys l to r | the xor of two prefix values |
| Windows inside the data allowance band | windows with a total from low to high | windows at most high minus windows at most low - 1 |
| Shared rides within the luggage limits | pairs with a sum from low to high | the same subtraction, with a pointer at each end of a sorted list |
| A listening session with variety limits | the longest run with at most k artists and at most cap plays of one | shrink from the left while either limit breaks |
The xor problem is the odd one out, and its idea is a table. Let P[i] be the xor of the first i masks. The deploys l to r toggle the flags in P[r + 1] xor P[l], because a flag that both prefixes share cancels out.
For the masks 5, 3 and 6 the prefixes are 0, 5, 6 and 0. The question [1, 2] gives P[3] xor P[1], which is 5, the same as 3 xor 6, and 5 has 2 bits set.
Exercise · Put it in order: Flags left on after a run of deploys. Arrange the lines into a function that returns, for each question, how many flags are on after the deploys l to r.
def flags_on_after(masks, ranges):
prefix = [0] * (len(masks) + 1)
for i in range(len(masks)):
prefix[i + 1] = prefix[i] ^ masks[i]
answers = []
for left, right in ranges:
toggled = prefix[right + 1] ^ prefix[left]
answers.append(bin(toggled).count("1"))
return answers
toggled = prefix[right] ^ prefix[left]A count inside a band is hard in one pass, because the left end of the window has two limits. A count of what is at most a limit is easy. So turn the first into the second.
Count what is at most high, subtract what is at most low minus 1, and run each count as one pass in which no pointer moves back.
Take the usage 2, 1, 3, 0, 4. Ten windows have a total of at most 4, and three have a total of at most 2. So 10 - 3 = 7 windows have a total from 3 to 4. For the lower side the limit is low minus 1 because a total of exactly 3 must stay in the band.
The "at most" pass moves a right end across the list. It adds the new value, and while the total is above the limit it drops the left value. Every window that ends at the right end and starts from left to right is allowed, so the pass adds right - left + 1.
Exercise · Predict the output: The window at each right end. This counts windows with a total of at most 4. It prints the number of allowed windows ending at each right end. What does it print?
usage = [2, 1, 3, 0, 4]
limit = 4
left = 0
total = 0
sizes = []
for right in range(len(usage)):
total += usage[right]
while total > limit:
total -= usage[left]
left += 1
sizes.append(right - left + 1)
print(*sizes)Count the windows at most high, subtract those at most low minus one, and the band is left.
Pairs work the same way on a sorted list, with a pointer at each end. When the lowest and the highest values add up to at most the limit, the lowest pairs with every value up to the highest. That is hi - lo pairs, and then the lowest is dropped. Otherwise the highest is too big for every partner left, so drop it.
Exercise · Find the bug: The lowest rider with one partner. The weights are sorted. This counts the pairs of riders whose weights add up to at most the limit. Which line is wrong?
def count_pairs_at_most(ordered, limit):
lo, hi = 0, len(ordered) - 1
count = 0
while lo < hi:
if ordered[lo] + ordered[hi] <= limit:
count += 1
lo += 1
else:
hi -= 1
return countThe Academy lessons Opposite ends, At most k, Prefix sums and Window counts gave you each pass. In the Academy a question asked for one limit. In a contest the question has a band, or two limits at once, and you build the answer from the passes you know.
Three things change. A band becomes a subtraction of two counts, and the lower limit is low minus 1. Two limits, such as at most k artists and at most cap plays, are fine in one window, because both only get worse as the window grows. And the shrink step needs values that are not negative.
The last change is easy to miss. Dropping the left value must never raise the total. Take the usage 3, -2 and 1, and the limit 2. The pass counts 3 allowed windows, but 5 windows have a total of at most 2.
The band has a second trap: the subtraction itself. Subtract the windows at most low instead of at most low - 1, and every window with a total of exactly low is lost. For the usage 1, 2 and 3 and the band 3 to 3, two windows have a total of 3, and the wrong subtraction gives 0.
Subtract the windows at most low minus one; subtracting at most low loses every total of exactly low.
Exercise · Break it: The band that loses its lower edge. The usage is never negative. This counts the windows whose total is from low to high. It subtracts the windows at most low from those at most high. Find an input where it is wrong.
def count_in_band(usage, low, high):
return at_most(usage, high) - at_most(usage, low)
def at_most(usage, limit):
left = 0
total = 0
count = 0
for right in range(len(usage)):
total += usage[right]
while total > limit and left <= right:
total -= usage[left]
left += 1
count += right - left + 1
return count| Limit | What it tells you |
|---|---|
| 10^5 minutes with usage up to 10^6 | totals up to 10^11, and up to 5,000,050,000 windows: use 64 bits |
| 10^5 riders | up to 4,999,950,000 pairs, so a 64-bit count, and one sort |
| 10^5 deploys with masks below 2^29 | a mask fits in 32 bits, and the prefix xors do too |
| 10^5 tracks and two limits | one window, each track entering and leaving once |
The full treatment is in Fast I/O and stress testing. Here the first line holds the count and the two band limits, and the second line the usage. The total and the answer are 64-bit in Java and C++.
import sys
def at_most(usage, limit):
if limit < 0:
return 0
left = 0
total = 0
count = 0
for right in range(len(usage)):
total += usage[right]
while total > limit:
total -= usage[left]
left += 1
count += right - left + 1
return count
def main():
data = sys.stdin.buffer.read().split()
n, low, high = int(data[0]), int(data[1]), int(data[2])
usage = list(map(int, data[3:3 + n]))
sys.stdout.write(str(at_most(usage, high) - at_most(usage, low - 1)) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
static long atMost(long[] usage, long limit) {
if (limit < 0) return 0;
int left = 0;
long total = 0, count = 0;
for (int right = 0; right < usage.length; right++) {
total += usage[right];
while (total > limit) total -= usage[left++];
count += right - left + 1;
}
return count;
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
long low = (long) in.nval;
in.nextToken();
long high = (long) in.nval;
long[] usage = new long[n];
for (int i = 0; i < n; i++) { in.nextToken(); usage[i] = (long) in.nval; }
System.out.println(atMost(usage, high) - atMost(usage, low - 1));
}
}#include <iostream>
#include <vector>
using namespace std;
long long atMost(const vector<long long>& usage, long long limit) {
if (limit < 0) return 0;
int left = 0;
long long total = 0, count = 0;
for (int right = 0; right < (int) usage.size(); right++) {
total += usage[right];
while (total > limit) total -= usage[left++];
count += right - left + 1;
}
return count;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
long long low, high;
cin >> n >> low >> high;
vector<long long> usage(n);
for (auto& x : usage) cin >> x;
cout << atMost(usage, high) - atMost(usage, low - 1) << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const [n, low, high] = data;
const usage = data.slice(3, 3 + n);
function atMost(limit) {
if (limit < 0) return 0;
let left = 0, total = 0, count = 0;
for (let right = 0; right < n; right++) {
total += usage[right];
while (total > limit) total -= usage[left++];
count += right - left + 1;
}
return count;
}
process.stdout.write(atMost(high) - atMost(low - 1) + "\n");On the sample of 5 minutes, usage 2, 1, 3, 0, 4 and the band 3 to 4, all four programs print 7.
The slow twin tries every window with two loops. The generator draws short lists of small usage values, so that totals land on the band edges often.
import random
from fast import count_windows_in_band
from slow import count_windows_in_band as slow_count
for seed in range(1000):
rng = random.Random(seed)
usage = [rng.randint(0, 6) for _ in range(rng.randint(1, 10))]
low = rng.randint(0, 12)
high = low + rng.randint(0, 8)
if count_windows_in_band(usage, low, high) != slow_count(usage, low, high):
print("different at", usage, low, high)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Subtract the windows at most low instead of at most low - 1, and the first seed already fails. The usage 6, 3, 0, 2, 4, 3, 3 with the band 12 to 16 gives 2 instead of 5.
At this band each pass is short, and the work is the reduction. Write the band as a subtraction before you code, and say what each pointer means. Aim for about 20 minutes a problem.
The ladder starts with the table, where each answer is two reads. The next two turn a band into two counts, one over windows and one over pairs. The last shrinks a window against two limits at once.
For each problem, write the reduction in one line before you code: a table read, a subtraction, or a shrink rule. Then build the slow twin, which is two nested loops, and stress test.
Checkpoint · Two pointers and prefix tricks
Q1/5 For the usage 2, 1, 3, 0, 4, ten windows have a total of at most 4 and three have a total of at most 2. How many windows have a total from 3 to 4?
Answer: B
The band from 3 to 4 holds the windows at most 4 minus the windows at most 3 - 1 = 2. That is 10 - 3 = 7.
Q2/5 The masks are 5, 3 and 6. How many flags are on after the deploys 1 to 2?
Answer: B
The prefix xors are 0, 5, 6 and 0. The range gives P[3] xor P[1] = 5, which has 2 bits set. It is also 3 xor 6.
Q3/5 The weights 1, 2 and 3 are sorted and the limit is 4. How many pairs have a sum of at most 4?
Answer: B
The pairs 1 and 2, and 1 and 3, fit. The pair 2 and 3 adds up to 5. The lowest value pairs with every value up to the highest that fits, so the pass adds hi - lo, not 1.
Q4/5 Why does the shrinking window miscount for the usage 3, -2 and 1 with the limit 2?
Answer: B
The pass counts 3 windows, but 5 have a total of at most 2. A shrinking window needs values that are not negative.
Q5/5 The usage is 1, 2, 3 and the band is 3 to 3. What goes wrong if you subtract the windows at most low, not at most low - 1?
Answer: B
The windows at most 3 include those with a total of exactly 3. Subtracting them removes the windows that belong to the band.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.