Data Structures & AlgorithmsHardICPC regional · Fenwick round
Problem: Count inversions in [2, 4, 1, 3, 5] with a Fenwick tree over the values.
Problem: Count inversions in [2, 4, 1, 3, 5] with a Fenwick tree over the values.
def inv(a):
n = max(a)
t = [0] * (n + 1)
def add(i):
while i <= n:
t[i] += 1
i += i & -i
def q(i):
s = 0
while i > 0:
s += t[i]
i -= i & -i
return s
res = 0
for seen, x in enumerate(a):
res += seen - q(x)
add(x)
return res
print(inv([2, 4, 1, 3, 5]))What is printed?- A. 2
- B. 3
- C. 4
- D. 5
Correct answer: B. 3
The inversions are (2,1), (4,1) and (4,3). Each step counts earlier elements that are greater than x as seen minus the number of earlier values at most x.
More Coding Interview Problems questions
- Problem: Run Bellman-Ford style negative-cycle detection (all distances start at 0, V - 1 rounds, then one extra check) on 3 vertices with…
- Problem: A directed graph has edges 0->1, 0->2, 1->2, 1->3, 2->3. Let A be its adjacency matrix. How many walks of exactly 3 edges go from…
- Problem: Undirected graph on 5 vertices has edges (0,1), (1,2), (2,0), (2,3), (3,4). Count the bridges by deleting each edge in turn and…
- Problem: Topological order by DFS finishing times (reverse postorder) for the DAG adj = {0: [1, 2], 1: [3], 2: [3], 3: []} on 4 vertices…
- Problem: Find the length of the longest common substring (contiguous) of 'abcdef' and 'zcdemn'. python def lcssub(a, b): best = 0 dp =…
- Problem: How many (possibly overlapping) occurrences of the pattern 'ana' are in 'banana'? python s = 'banana' p = 'ana' print(sum(1 for i…