Skip to content

add_edge -> increase_capacity #5

@thorehusfeldt

Description

@thorehusfeldt

This just bit me in the ass when I solved elementarymath (and added the “same” edge twice). The chanced name avoids this mistake, I think.

def add_edge(self, i, j, w):

Also, dfs can be made local to max_flow. This again saves some typing and makes the structure clearer:

class Flow:
    def __init__(self, nvertices):
        self.G = [defaultdict(int) for _ in range(nvertices)]

    def increase_capacity(self, u, v, cap):
        self.G[u][v] += cap

    def max_flow(self, source, to):

        def dfs(u, hi):
            if u in self.reached:
                return 0
            if u == to:
                return hi
            G = self.G
            self.reached.add(u)
            for v, cap in G[u].items():
                if cap:
                    f = dfs(v, min(hi, cap))
                    if f:
                        G[u][v] -= f
                        G[v][u] += f
                        return f
            return 0

        flow = 0
        while True:
            self.reached = set()
            pushed = dfs(source, float("inf"))
            if not pushed:
                break
            flow += pushed
        return flow # cut = self.reached, f(u,v) = cap(u,v) - self.G[u][v]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions