Graph Theory37 sections · 1633 units
Open in Course

Implementation - Distinct Routes - Implement Solution

(CSES 1711)

Here is the complete distinct routes solution:

function solve(n, m, edges):
    // Build adjacency list and capacity
    adj = array of n empty lists
    capacity = map from (u,v) to int
    flow = map from (u,v) to int, all 0

    for (u, v) in edges:
        adj[u].append(v)
        adj[v].append(u)
        capacity[(u,v)] = capacity[(u,v)] + 1

    // Dinic's max flow
    maxFlow = 0
    while bfsLevelGraph():
        while true:
            f = dfsBlocking(1, infinity)
            if f == 0:
                break
            maxFlow = maxFlow + f

    // Extract paths
    paths = empty list
    for i from 1 to maxFlow:
        path = tracePath(1, n, flow)
        paths.append(path)

    print maxFlow
    for path in paths:
        print path.length, path

Time: O(V2E)O(V^2 E). Space: O(V+E)O(V + E).