This repository has been archived on 2022-06-22. You can view files and clone it, but cannot push or open issues or pull requests.
usaco-guide/content/6_Plat/2_Plat_1DRQ.md
2020-06-15 16:19:07 -07:00

4.3 KiB

id title author prerequisites
1DRQ 1D Range Queries Benjamin Qi
Gold - Binary Indexed Trees

General range queries for associative operations, including segment tree.

Static Range Queries

Given a static array A[1],A[2],\ldots,A[N], you want to answer queries in the form A[l]\ominus A[l+1]\ominus \cdots \ominus A[r] in O(1) time each with O(N\log N) time preprocessing, where \ominus denotes any associative operation. In the case when \ominus denotes min, preprocessing can be done in O(1) time.

Tutorial

Divide & Conquer

Divide & conquer can refer to many different techniques. In this case, we use it to answer Q queries offline in O((N+Q)\log N) time.

Suppose that all queries satisfiy L\le l\le r\le R (initially, L=1 and R=N). Letting M=\left\lfloor \frac{L+R}{2}\right\rfloor, we can compute

lef[l]=A[l]\ominus A[l+1]\ominus \cdots \ominus A[M]

for all L\le l\le M and

rig[r]=A[M+1]\ominus A[M+2] \ominus \cdots\ominus A[r]

for each M< r\le R. Then the answer for all queries satisfying l\le M<r is simply lef[l]\ominus rig[r] due to the associativity condition. After that, we recurse on all query intervals completely contained within [L,M] and [M+1,R] independently.

Actually, this can be adjusted to answer queries online in O(1) time each. See my implementation here.

See my implementation here.

Problems

Segment Tree

Author: Benjamin Qi

This data structure allows you to do point update and range query in O(\log N) time each for any associative operation. In particular, note that lazy updates allow you to range updates as well.

Tutorials

Problems

BIT Revisited

Binary Indexed Trees can support range increments in addition to range sum queries.

Example problem: