CP Workshop Day 2
CP Workshop Day 2
Day 2
13 April 2025
Prefix Sum
1
USACO Guide
Prefix Sum
1
USACO Guide
Prefix Sum
1
USACO Guide
Prefix Sum
2
USACO Guide
Prefix Sum
2
USACO Guide
Static Range Sum Query
3
USACO Guide
Problem 1
▶ Given:
▶ String s of length n (2 ≤ n ≤ 105 )
▶ Characters are either ’.’ or ’#’
▶ m queries (1 ≤ m ≤ 105 )
▶ Query:
▶ Two indices li , ri (1 ≤ li < ri ≤ n)
▶ Count indices i where s[i] = s[i + 1] in [li , ri )
▶ Output:
▶ Answer all queries in order
Difference Array Technique
Efficient Range Updates
▶ Purpose:
▶ Range Update: add x to all values in range [l, r ]
▶ Perform range updates in constant time
▶ Convert to final array in linear time
Difference Array Technique
Efficient Range Updates
▶ Purpose:
▶ Range Update: add x to all values in range [l, r ]
▶ Perform range updates in constant time
▶ Convert to final array in linear time
▶ Steps:
▶ For update [l, r ] + val:
▶ D[l] += val
▶ D[r + 1] −= val
▶ Compute final array using prefix sum technique
Problem 2
▶ Given:
▶ Array A of n elements (1 ≤ n ≤ 2 × 105 )
▶ q queries (1 ≤ q ≤ 2 × 105 )
▶ Query:
▶ Range [li , ri ]
▶ Returns sum A[li ] + A[li + 1] + · · · + A[ri ]
▶ Challenge:
▶ Reorder array elements to maximize total sum of all query
answers
Problem 3
▶ Given:
▶ Initial array A of size n (1 ≤ n ≤ 105 )
▶ m range operations (1 ≤ m ≤ 105 )
▶ k queries (1 ≤ k ≤ 105 )
▶ Operations:
▶ Operation i: Add di to A[li ..ri ]
▶ Queries:
▶ Query j: Apply operations xj to yj
▶ Output:
▶ Final array after all queries
2D Prefix Sum
a X
X b
prefix[a][b] = arr[i][j].
i=1 j=1
2D Prefix Sum
a X
X b
prefix[a][b] = arr[i][j].
i=1 j=1
A X
X B
arr[i][j] = prefix[A][B] − prefix[a − 1][B]
i=a j=b
▶ Given:
▶ Input matrix I of size n × m (1 ≤ n, m ≤ 103 )
▶ Kernel size k × l (1 ≤ k ≤ n, 1 ≤ l ≤ m)
▶ Kernel elements restricted to −1, 0, 1
▶ Operation:
▶ 2D convolution:
Pk Pl
O(p, q) = x=1 y =1 K (x, y ) × I (p + x − 1, q + y − 1)
▶ Output matrix size: (n − k + 1) × (m − l + 1)
▶ Challenge:
▶ Find the maximum sum of all elements in the output matrix O
among all possible matrix K
Problem 5
▶ Scenario:
▶ Street with n sights at positions 1, 2, . . . , n miles
▶ Sight at position i has beauty bi
▶ Task:
▶ Choose jog interval [l, r ] with at least 3 sights
▶ Maximize: sum(3 max beauties) − (r − l)
▶ Constraints:
▶ t ≤ 105 test cases
▶ 5
P≤ 10 per
n test case
▶ n ≤ 105
▶ 1 ≤ bi ≤ 108
Monotone stack
Step 0: 2 1 4 5 3 4 1 2
Step 1: 2 1 4 5 3 4 1 2
Step 2: 2 1 4 5 3 4 1 2
Step 3: 2 1 4 5 3 4 1 2
Step 4: 2 1 4 5 3 4 1 2
Step 5: 2 1 4 5 3 4 1 2
Sliding Window Minimum
Problem 1
4
Antti Laaksonen, Competitive Programmer’s Handbook, Chapter 8.3, 2018.
Sliding Window Minimum
Problem 1
4
Antti Laaksonen, Competitive Programmer’s Handbook, Chapter 8.3, 2018.
Time Complexity
Problem 1