Graph Theory37 sections · 1633 units
Open in Course

Fixed-Length Paths II - Implementation

(Range counting with map)

Here is the solution:

function count_through_centroid(c, adj, k1, k2)
    distances := get_distances(c, adj)
    count := 0
    freq := map from distance to count
    for d in distances
        for target from k1 - d to k2 - d
            count := count + freq[target]
            freq[d] := freq[d] + 1
            return count

You need a data structure supporting range queries like a BIT or balanced tree.

This runs in O(nlogn)O(n \log n) time and uses O(n)O(n) space.