Problem:
Maximum Flow A flow network is a directed graph which has a $source$ and a $sink$. In a flow network, each edge $(u, v)$ has a capacity $c(u, v)$. Each edge receives a flow, but the amount of flow on the edge can not exceed the corresponding capacity. Find the maximum flow from the $source$ to the $sink$. Input A flow network is given in the following format. $|V|$, $|E|$ is the number of vertices and edges of the flow network respectively. The vertices in $G$ are named with the numbers 0, 1,..., $|V|-1$. The source is 0 and the sink is $|V|-1$. $u_i$, $v_i$, $c_i$ represent $i$-th edge of the flow network.
A pair of $u_i$ and $v_i$ denotes that there is an edge from $u_i$ to $v_i$ and $c_i$ is the capacity of $i$-th edge. Output Print the maximum flow. Constraints  $2 \leq |V| \leq 100$  $1 \leq |E| \leq 1000$  $0 \leq c_i \leq 10000$  Sample Input 1 4 5
0 1 2
0 2 1
1 2 1
1 3 1
2 3 2 Sample Output 1 3

Solution (Python):
class FordFulkerson:
    """Ford-Fulkerson Algorithm: find max-flow
       complexity: O(FE) (F: max flow)
    """
    class edge:
        def __init__(self, to, cap, rev):
            self.to, self.cap, self.rev = to, cap, rev

    def __init__(self, V, E, source, sink):
        """ V: the number of vertexes
            E: adjacency list
            source: start point
            sink: goal point
        """
        self.V = V
        self.E = [[] for _ in range(V)]
        for fr in range(V):
            for to, cap in E[fr]:
                self.E[fr].append(self.edge(to, cap, len(self.E[to])))
                self.E[to].append(self.edge(fr, 0, len(self.E[fr])-1))
        self.maxflow = self.ford_fulkerson(source, sink)

    def ford_fulkerson(self, source, sink, INF=10**9):
        """find max-flow"""
        def dfs(vertex, sink, flow):
            """find augmenting path"""
            if vertex == sink:
                return flow
            used[vertex] = True
            for i, e in enumerate(self.E[vertex]):
                if not used[e.to] and e.cap > 0:
                    d = dfs(e.to, sink, min(flow, e.cap))
                    if d > 0:
                        self.E[vertex][i].cap -= d
                        self.E[e.to][e.rev].cap += d
                        return d
            return 0

        maxflow = 0
        while True:
            used = [False] * self.V
            flow = dfs(source, sink, INF)
            if flow == 0:
                return maxflow
            else:
                maxflow += flow

V, E = map(int, input().split())
edge = [[] for _ in range(V)]
for _ in range(E):
    u, v, cap = map(int, input().split())
    edge[u].append((v, cap))
print(FordFulkerson(V, edge, 0, V-1).maxflow)

Solution (Python):
class FordFulkerson:
    """Ford-Fulkerson Algorithm: find max-flow
       complexity: O(FE) (F: max flow)
    """
    class edge:
        def __init__(self, to, cap, rev):
            self.to, self.cap, self.rev = to, cap, rev

    def __init__(self, V, E, source, sink):
        """ V: the number of vertexes
            E: adjacency list
            source: start point
            sink: goal point
        """
        self.V = V
        self.E = [[] for _ in range(V)]
        for fr in range(V):
            for to, cap in E[fr]:
                self.E[fr].append(self.edge(to, cap, len(self.E[to])))
                self.E[to].append(self.edge(fr, 0, len(self.E[fr])-1))
        self.maxflow = self.ford_fulkerson(source, sink)

    def ford_fulkerson(self, source, sink):
        """find max-flow"""
        INF = float('inf')
        maxflow = 0
        while True:
            self.used = [False] * self.V
            flow = self.dfs(source, sink, INF)
            if flow == 0:
                return maxflow
            else:
                maxflow += flow

    def dfs(self, vertex, sink, flow):
        """find augmenting path"""
        if vertex == sink:
            return flow
        self.used[vertex] = True
        for i, e in enumerate(self.E[vertex]):
            if not self.used[e.to] and e.cap > 0:
                d = self.dfs(e.to, sink, min(flow, e.cap))
                if d > 0:
                    self.E[vertex][i].cap -= d
                    self.E[e.to][e.rev].cap += d
                    return d
        return 0

V, E = map(int, input().split())
edge = [[] for _ in range(V)]
for _ in range(E):
    u, v, cap = map(int, input().split())
    edge[u].append((v, cap))
print(FordFulkerson(V, edge, 0, V-1).maxflow)

Solution (Python):
from collections import deque
class Dinic:
    """Dinic Algorithm: find max-flow
       complexity: O(EV^2)
    """
    class edge:
        def __init__(self, to, cap, rev):
            self.to, self.cap, self.rev = to, cap, rev

    def __init__(self, V, E, source, sink):
        """ V: the number of vertexes
            E: adjacency list
            source: start point
            sink: goal point
        """
        self.V = V
        self.E = [[] for _ in range(V)]
        for fr in range(V):
            for to, cap in E[fr]:
                self.E[fr].append(self.edge(to, cap, len(self.E[to])))
                self.E[to].append(self.edge(fr, 0, len(self.E[fr])-1))
        self.maxflow = self.dinic(source, sink)

    def dinic(self, source, sink):
        """find max-flow"""
        INF = float('inf')
        maxflow = 0
        while True:
            self.bfs(source)
            if self.level[sink] < 0:
                return maxflow
            self.itr = [0] * self.V
            while True:
                flow = self.dfs(source, sink, INF)
                if flow > 0:
                    maxflow += flow
                else:
                    break            

    def dfs(self, vertex, sink, flow):
        """find augmenting path"""
        if vertex == sink:
            return flow
        for i in range(self.itr[vertex], len(self.E[vertex])):
            self.itr[vertex] = i
            e = self.E[vertex][i]
            if e.cap > 0 and self.level[vertex] < self.level[e.to]:
                d = self.dfs(e.to, sink, min(flow, e.cap))
                if d > 0:
                    self.E[vertex][i].cap -= d
                    self.E[e.to][e.rev].cap += d
                    return d
        return 0

    def bfs(self, start):
        """find shortest path from start"""
        que = deque()
        self.level = [-1] * self.V
        que.append(start)
        self.level[start] = 0
        
        while que:
            fr = que.popleft()
            for e in self.E[fr]:
                if e.cap > 0 and self.level[e.to] < 0:
                    self.level[e.to] = self.level[fr] + 1
                    que.append(e.to)        

V, E = map(int, input().split())
edge = [[] for _ in range(V)]
for _ in range(E):
    u, v, cap = map(int, input().split())
    edge[u].append((v, cap))
print(Dinic(V, edge, 0, V-1).maxflow)

Solution (Python):
from collections import deque
class Dinic:
    """Dinic Algorithm: find max-flow
       complexity: O(EV^2)
    """
    class edge:
        def __init__(self, to, cap, rev):
            self.to, self.cap, self.rev = to, cap, rev

    def __init__(self, V, E, source, sink):
        """ V: the number of vertexes
            E: adjacency list
            source: start point
            sink: goal point
        """
        self.V = V
        self.E = [[] for _ in range(V)]
        for fr in range(V):
            for to, cap in E[fr]:
                self.E[fr].append(self.edge(to, cap, len(self.E[to])))
                self.E[to].append(self.edge(fr, 0, len(self.E[fr])-1))
        self.maxflow = self.dinic(source, sink)

    def dinic(self, source, sink):
        """find max-flow"""
        INF = float('inf')
        maxflow = 0
        while True:
            self.bfs(source)
            if self.level[sink] == -1:
                return maxflow
            self.itr = [0] * self.V
            while True:
                flow = self.dfs(source, sink, INF)
                if flow > 0:
                    maxflow += flow
                else:
                    break            

    def dfs(self, vertex, sink, flow):
        """find augmenting path"""
        if vertex == sink:
            return flow
        for i in range(self.itr[vertex], len(self.E[vertex])):
            self.itr[vertex] = i
            e = self.E[vertex][i]
            if e.cap > 0 and self.level[vertex] < self.level[e.to]:
                d = self.dfs(e.to, sink, min(flow, e.cap))
                if d > 0:
                    e.cap -= d
                    self.E[e.to][e.rev].cap += d
                    return d
        return 0

    def bfs(self, start):
        """find shortest path from start"""
        que = deque()
        self.level = [-1] * self.V
        que.append(start)
        self.level[start] = 0
        
        while que:
            fr = que.popleft()
            for e in self.E[fr]:
                if e.cap > 0 and self.level[e.to] == -1:
                    self.level[e.to] = self.level[fr] + 1
                    que.append(e.to)        

V, E = map(int, input().split())
edge = [[] for _ in range(V)]
for _ in range(E):
    u, v, cap = map(int, input().split())
    edge[u].append((v, cap))
print(Dinic(V, edge, 0, V-1).maxflow)

Solution (Python):
import sys
from queue import deque

sys.setrecursionlimit(200000)


def hierarchize(source):
    global edges, hierarchy
    hierarchy = [-1] * n
    queue = deque([(0, source)])
    while queue:
        h, v = queue.popleft()
        if hierarchy[v] != -1:
            continue
        hierarchy[v] = h
        if v == sink:
            return True
        queue.extend((h + 1, target)
                     for remain, target, _ in edges[v] if hierarchy[target] == -1 and remain)
    return False


def augment(v, limit):
    global sink, edges, hierarchy
    if v == sink:
        return limit
    res = 0
    for e in edges[v]:
        remain, target, idx = e
        if remain == 0 or hierarchy[v] >= hierarchy[target]:
            continue
        aug = augment(target, min(limit, remain))
        e[0] -= aug
        edges[target][idx][0] += aug
        res += aug
        limit -= aug
        if not limit:
            break
    return res


n, m = map(int, input().split())
sink = n - 1
edges = [[] for _ in range(n)]

hierarchy = [-1] * n

for _ in range(m):
    s, t, c = map(int, input().split())
    es, et = edges[s], edges[t]
    ls, lt = len(es), len(et)
    edges[s].append([c, t, lt])
    edges[t].append([0, s, ls])

res = 0
while hierarchize(0):
    res += augment(0, 10000001)
print(res)

Solution (Python):
from collections import deque

class Dinic:
    class edge:
        def __init__(self,to,cap,rev):
            self.to,self.cap,self.rev=to,cap,rev

    def __init__(self,v):
        self.numv=v
        self.G=[[] for _ in range(self.numv)]

    def add(self,fr,to,cap):
        self.G[fr].append(self.edge(to,cap,len(self.G[to])))
        self.G[to].append(self.edge(fr,0,len(self.G[fr])-1))

    def bfs(self,s):
        self.level=[-1]*self.numv
        self.level[s]=0
        que=deque()
        que.append(s)
        while len(que)!=0:
            v=que.popleft()
            for i in range(len(self.G[v])):
                e=self.G[v][i]
                if e.cap>0 and self.level[e.to]<0:
                    self.level[e.to]=self.level[v]+1
                    que.append(e.to)

    def dfs(self,v,t,f):
        if v==t:return f
        for i in range(self.iter[v],len(self.G[v])):
            self.iter[v]=i
            e=self.G[v][i]
            if e.cap>0 and self.level[v]<self.level[e.to]:
                d=self.dfs(e.to,t,min(f,e.cap))
                if d>0:
                    e.cap-=d
                    self.G[e.to][e.rev].cap+=d
                    return d
        return 0

    def max_flow(self,s,t):
        flow=0
        inf=float('inf')
        while 1:
            self.bfs(s)
            if self.level[t]<0:return flow
            self.iter=[0]*self.numv
            f=self.dfs(s,t,inf)
            while f>0:
                flow+=f
                f=self.dfs(s,t,inf)

V,E=map(int,input().split())
MF=Dinic(V)
for i in range(E):
    u,v,c=map(int,input().split())
    MF.add(u,v,c)
print(MF.max_flow(0,V-1))

Solution (Python):
from collections import deque

class Dinic:
    class edge:
        def __init__(self,to,cap,rev):
            self.to,self.cap,self.rev=to,cap,rev

    def __init__(self,v):
        self.numv=v
        self.G=[[] for _ in xrange(self.numv)]

    def add(self,fr,to,cap):
        self.G[fr].append(self.edge(to,cap,len(self.G[to])))
        self.G[to].append(self.edge(fr,0,len(self.G[fr])-1))

    def bfs(self,s):
        self.level=[-1]*self.numv
        self.level[s]=0
        que=deque()
        que.append(s)
        while len(que)!=0:
            v=que.popleft()
            for i in xrange(len(self.G[v])):
                e=self.G[v][i]
                if e.cap>0 and self.level[e.to]<0:
                    self.level[e.to]=self.level[v]+1
                    que.append(e.to)

    def dfs(self,v,t,f):
        if v==t:return f
        for i in xrange(self.iter[v],len(self.G[v])):
            self.iter[v]=i
            e=self.G[v][i]
            if e.cap>0 and self.level[v]<self.level[e.to]:
                d=self.dfs(e.to,t,min(f,e.cap))
                if d>0:
                    e.cap-=d
                    self.G[e.to][e.rev].cap+=d
                    return d
        return 0

    def max_flow(self,s,t):
        flow=0
        inf=float('inf')
        while 1:
            self.bfs(s)
            if self.level[t]<0:return flow
            self.iter=[0]*self.numv
            f=self.dfs(s,t,inf)
            while f>0:
                flow+=f
                f=self.dfs(s,t,inf)

V,E=map(int,raw_input().split())
MF=Dinic(V)
for i in xrange(E):
    u,v,c=map(int,raw_input().split())
    MF.add(u,v,c)
print(MF.max_flow(0,V-1))

Solution (Python):





import collections
import sys


REC_LIMIT = 10000
INF = 10 ** 8


class Edge(object):

    def __init__(self, source, sink, capacity):
        self.source = source
        self.sink = sink
        self.capacity = capacity
        self.rev_edge = None

    def __str__(self):
        return "Edge {} -> {} : {}".format(self.source,
                                           self.sink, self.capacity)


class FlowNetwork(object):

    def __init__(self):
        self.adj_edges = collections.defaultdict(list)
        self.flow = dict()
        self.used_edge = None

    def get_edges_from(self, vertex):
        return self.adj_edges[vertex]

    def add_edge(self, source, sink, capacity):
        assert source != sink
        f_edge = Edge(source, sink, capacity)
        b_edge = Edge(sink, source, 0)
        f_edge.rev_edge = b_edge
        b_edge.rev_edge = f_edge
        self.adj_edges[source].append(f_edge)
        self.adj_edges[sink].append(b_edge)
        self.flow[f_edge] = 0
        self.flow[b_edge] = 0

    def dfs(self, source, sink, flow):
        if source == sink:
            return flow
        self.used_edge[source] = True
        for edge in self.get_edges_from(source):
            residual = edge.capacity - self.flow[edge]
            if self.used_edge[edge.sink] or residual <= 0:
                continue
            d = self.dfs(edge.sink, sink, min(flow, residual))
            if d > 0:
                self.flow[edge] += d
                self.flow[edge.rev_edge] -= d
                return d
        return 0

    def ford_fulkerson(self, source, sink):
        max_flow = 0
        while True:
            self.used_edge = collections.defaultdict(bool)
            df = self.dfs(source, sink, INF)
            if df == 0:
                return max_flow
            else:
                max_flow += df


def main():
    sys.setrecursionlimit(REC_LIMIT)
    v, e = map(int, input().split())
    network = FlowNetwork()
    for _ in range(e):
        network.add_edge(*map(int, input().split()))
    mf = network.ford_fulkerson(0, v - 1)
    print(mf)


if __name__ == '__main__':
    main()

Solution (Python):





import array
import collections
import sys


REC_LIMIT = 10000
INF = 10 ** 8


Edge = collections.namedtuple("Edge", "source sink capacity")


class FlowNetwork(object):

    def __init__(self, num_vertices):
        self.adj_edges = [set() for _ in range(num_vertices)]
        self.flow = None
        self.rev_edge = dict()
        self.used = None

    def get_edges_from(self, vertex):
        return self.adj_edges[vertex]

    def add_edge(self, source, sink, capacity):
        assert source != sink
        forward_edge = Edge(source, sink, capacity)
        backward_edge = Edge(sink, source, 0)
        self.rev_edge[forward_edge] = backward_edge
        self.rev_edge[backward_edge] = forward_edge
        self.adj_edges[source].add(forward_edge)
        self.adj_edges[sink].add(backward_edge)

    def dfs(self, source, sink, flow):
        if source == sink:
            return flow
        self.used[source] = True
        for edge in self.get_edges_from(source):
            rest = edge.capacity - self.flow[edge]
            if self.used[edge.sink] or rest <= 0:
                continue
            d = self.dfs(edge.sink, sink, min(flow, rest))
            if d > 0:
                self.flow[edge] += d
                self.flow[self.rev_edge[edge]] -= d
                return d
        return 0

    def ford_fulkerson(self, source, sink):
        self.flow = collections.defaultdict(int)
        max_flow = 0
        while True:
            self.used = collections.defaultdict(bool)
            df = self.dfs(source, sink, INF)
            if df == 0:
                return max_flow
            else:
                max_flow += df


def main():
    sys.setrecursionlimit(REC_LIMIT)
    v, e = map(int, input().split())
    network = FlowNetwork(v)
    for _ in range(e):
        network.add_edge(*map(int, input().split()))
    mf = network.ford_fulkerson(0, v - 1)
    print(mf)


if __name__ == '__main__':
    main()

Solution (Python):
import collections


class MaxFlow:
    """Dinic Algorithm: find max-flow
       complexity: O(EV^2)
       used in GRL6A(AOJ)
    """
    class Edge:
        def __init__(self, to, cap, rev):
            self.to, self.cap, self.rev = to, cap, rev

    def __init__(self, V):
        """ V: the number of vertexes
            E: adjacency list
            source: start point
            sink: goal point
        """
        self.V = V
        self.E = [[] for _ in range(V)]

    def add_edge(self, fr, to, cap):
        self.E[fr].append(self.Edge(to, cap, len(self.E[to])))
        self.E[to].append(self.Edge(fr, 0, len(self.E[fr])-1))

    def dinic(self, source, sink):
        """find max-flow"""
        INF = float('inf')
        maxflow = 0
        while True:
            self.bfs(source)
            if self.level[sink] < 0:
                return maxflow
            self.itr = [0] * self.V
            while True:
                flow = self.dfs(source, sink, INF)
                if flow > 0:
                    maxflow += flow
                else:
                    break

    def dfs(self, vertex, sink, flow):
        """find augmenting path"""
        if vertex == sink:
            return flow
        for i in range(self.itr[vertex], len(self.E[vertex])):
            self.itr[vertex] = i
            e = self.E[vertex][i]
            if e.cap > 0 and self.level[vertex] < self.level[e.to]:
                d = self.dfs(e.to, sink, min(flow, e.cap))
                if d > 0:
                    e.cap -= d
                    self.E[e.to][e.rev].cap += d
                    return d
        return 0

    def bfs(self, start):
        """find shortest path from start"""
        que = collections.deque()
        self.level = [-1] * self.V
        que.append(start)
        self.level[start] = 0

        while que:
            fr = que.popleft()
            for e in self.E[fr]:
                if e.cap > 0 and self.level[e.to] < 0:
                    self.level[e.to] = self.level[fr] + 1
                    que.append(e.to)

V, E = map(int, input().split())
mf = MaxFlow(V)
source, sink = 0, V-1

for _ in range(E):
    s, t, c = map(int, input().split())
    mf.add_edge(s, t, c)
print(mf.dinic(source, sink))

Solution (Python):



"""
input:
4 5
0 1 2
0 2 1
1 2 1
1 3 1
2 3 2

output:
3
"""

import sys
from collections import deque


def graph_bfs(source, target, parent):
    visited = [False] * vertices
    queue = deque()
    queue.append(source)
    visited[source] = True

    while queue:
        current = queue.popleft()
        for adj, cp in adj_table[current].items():
            if not visited[adj] and cp > 0:
                queue.append(adj)
                visited[adj] = True
                parent[adj] = current

    return True if visited[target] else False


def graphFordFulkerson(source, sink):
    parent = [-1] * vertices
    max_flow = 0

    while graph_bfs(source, sink, parent):
        path_flow = float('inf')

        bk_1 = sink
        while bk_1 != source:
            path_flow = min(path_flow, adj_table[parent[bk_1]][bk_1])
            bk_1 = parent[bk_1]

        max_flow += path_flow

        bk_2 = sink
        while bk_2 != source:
            parent_bk_2 = parent[bk_2]
            adj_table[parent_bk_2].setdefault(bk_2, 0)
            adj_table[bk_2].setdefault(parent_bk_2, 0)

            
            adj_table[parent_bk_2][bk_2] -= path_flow
            adj_table[bk_2][parent_bk_2] += path_flow
            bk_2 = parent[bk_2]

    return max_flow


def generate_adj_table(v_table):
    for each in v_table:
        source, target, cp = map(int, each)
        init_adj_table[source][target] = cp

    return init_adj_table


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices, edges = map(int, _input[0].split())
    v_info = map(lambda x: x.split(), _input[1:])

    init_adj_table = [dict() for _ in range(vertices)]
    adj_table = generate_adj_table(v_info)
    ans = graphFordFulkerson(source=0, sink=vertices - 1)
    print(ans)

Solution (Python):



"""
input:
4 5
0 1 2
0 2 1
1 2 1
1 3 1
2 3 2

output:
3
"""

import sys
from collections import deque


def graph_bfs(source, target, parent):
    visited = [False] * vertices
    queue = deque()
    queue.append(source)
    visited[source] = True

    while queue:
        current = queue.popleft()
        for adj, cp in adj_table[current].items():
            if not visited[adj] and cp > 0:
                queue.append(adj)
                visited[adj] = True
                parent[adj] = current

    return True if visited[target] else False


def graphFordFulkerson(source, sink):
    parent = [-1] * vertices
    max_flow = 0

    while graph_bfs(source, sink, parent):
        path_flow = float('inf')

        bk_1 = sink
        while bk_1 is not source:
            path_flow = min(path_flow, adj_table[parent[bk_1]][bk_1])
            bk_1 = parent[bk_1]

        max_flow += path_flow

        bk_2 = sink
        while bk_2 is not source:
            parent_bk_2 = parent[bk_2]
            adj_table[parent_bk_2].setdefault(bk_2, 0)
            adj_table[bk_2].setdefault(parent_bk_2, 0)

            
            adj_table[parent_bk_2][bk_2] -= path_flow
            adj_table[bk_2][parent_bk_2] += path_flow
            bk_2 = parent[bk_2]

    return max_flow


def generate_adj_table(v_table):
    for each in v_table:
        source, target, cp = map(int, each)
        init_adj_table[source][target] = cp

    return init_adj_table


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices, edges = map(int, _input[0].split())
    v_info = map(lambda x: x.split(), _input[1:])

    init_adj_table = [dict() for _ in range(vertices)]
    adj_table = generate_adj_table(v_info)
    ans = graphFordFulkerson(source=0, sink=vertices - 1)
    print(ans)

Solution (Python):



"""
input:
4 5
0 1 2
0 2 1
1 2 1
1 3 1
2 3 2

output:
3
"""

import sys
from collections import deque


def graph_bfs(source, target, parent):
    visited = [False] * vertices
    queue = deque()
    queue.append(source)
    visited[source] = True

    while queue:
        current = queue.popleft()
        for adj, cp in adj_table[current].items():
            if not visited[adj] and cp > 0:
                queue.append(adj)
                visited[adj] = True
                parent[adj] = current

    return True if visited[target] else False


def graphFordFulkerson(source, sink):
    parent = [-1] * vertices
    max_flow = 0

    while graph_bfs(source, sink, parent):
        path_flow = float('inf')

        bk_1 = sink
        while bk_1 is not source:
            path_flow = min(path_flow, adj_table[parent[bk_1]][bk_1])
            bk_1 = parent[bk_1]

        max_flow += path_flow

        bk_2 = sink
        while bk_2 is not source:
            parent_bk_2 = parent[bk_2]
            adj_table[parent_bk_2].setdefault(bk_2, 0)
            adj_table[bk_2].setdefault(parent_bk_2, 0)

            
            adj_table[parent_bk_2][bk_2] -= path_flow
            adj_table[bk_2][parent_bk_2] += path_flow
            bk_2 = parent[bk_2]

    return max_flow


def generate_adj_table(v_table):
    for each in v_table:
        source, target, cp = map(int, each)
        init_adj_table[source][target] = cp

    return init_adj_table


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices, edges = map(int, _input[0].split())
    v_info = map(lambda x: x.split(), _input[1:])

    init_adj_table = [dict() for _ in range(vertices)]
    adj_table = generate_adj_table(v_info)
    ans = graphFordFulkerson(source=0, sink=vertices - 1)
    print(ans)

Solution (Python):



"""
input:
4 5
0 1 2
0 2 1
1 2 1
1 3 1
2 3 2

output:
3
"""

import sys
from collections import deque


def graph_bfs(source, target, parent):
    visited = [False] * vertices
    queue = deque()
    queue.append(source)
    visited[source] = True

    while queue:
        current = queue.popleft()
        for adj, cp in adj_table[current].items():
            if not visited[adj] and cp:
                queue.append(adj)
                visited[adj] = True
                parent[adj] = current

    return True if visited[target] else False


def graphFordFulkerson(source, sink):
    parent = [-1] * vertices
    max_flow = 0

    while graph_bfs(source, sink, parent):
        path_flow = float('inf')

        bk_1 = sink
        while bk_1 is not source:
            path_flow = min(path_flow, adj_table[parent[bk_1]][bk_1])
            bk_1 = parent[bk_1]

        max_flow += path_flow

        bk_2 = sink
        while bk_2 is not source:
            parent_bk_2 = parent[bk_2]
            adj_table[parent_bk_2].setdefault(bk_2, 0)
            adj_table[bk_2].setdefault(parent_bk_2, 0)

            
            adj_table[parent_bk_2][bk_2] -= path_flow
            adj_table[bk_2][parent_bk_2] += path_flow
            bk_2 = parent[bk_2]

    return max_flow


def generate_adj_table(v_table):
    for each in v_table:
        source, target, cp = map(int, each)
        init_adj_table[source][target] = cp

    return init_adj_table


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices, edges = map(int, _input[0].split())
    v_info = map(lambda x: x.split(), _input[1:])

    init_adj_table = [dict() for _ in range(vertices)]
    adj_table = generate_adj_table(v_info)
    ans = graphFordFulkerson(source=0, sink=vertices - 1)
    print(ans)

Solution (Python):



"""
input:
4 5
0 1 2
0 2 1
1 2 1
1 3 1
2 3 2

output:
3
"""

import sys
from collections import deque


def graph_bfs(source, target, parent):
    visited = [False] * vertices
    queue = deque()
    queue.append(source)
    visited[source] = True

    while queue:
        current = queue.popleft()
        for adj, cp in adj_table[current].items():
            if cp and not visited[adj]:
                queue.append(adj)
                visited[adj] = True
                parent[adj] = current

    return True if visited[target] else False


def graphFordFulkerson(source, sink):
    parent = [-1] * vertices
    max_flow = 0

    while graph_bfs(source, sink, parent):
        path_flow = float('inf')

        bk_1 = sink
        while bk_1 is not source:
            path_flow = min(path_flow, adj_table[parent[bk_1]][bk_1])
            bk_1 = parent[bk_1]

        max_flow += path_flow

        bk_2 = sink
        while bk_2 is not source:
            parent_bk_2 = parent[bk_2]
            adj_table[parent_bk_2].setdefault(bk_2, 0)
            adj_table[bk_2].setdefault(parent_bk_2, 0)

            
            adj_table[parent_bk_2][bk_2] -= path_flow
            adj_table[bk_2][parent_bk_2] += path_flow
            bk_2 = parent[bk_2]

    return max_flow


def generate_adj_table(v_table):
    for each in v_table:
        source, target, cp = map(int, each)
        init_adj_table[source][target] = cp

    return init_adj_table


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices, edges = map(int, _input[0].split())
    v_info = map(lambda x: x.split(), _input[1:])

    init_adj_table = [dict() for _ in range(vertices)]
    adj_table = generate_adj_table(v_info)
    ans = graphFordFulkerson(source=0, sink=vertices - 1)
    print(ans)

Solution (Python):



"""
input:
4 5
0 1 2
0 2 1
1 2 1
1 3 1
2 3 2

output:
3
"""

import sys
from collections import deque


def graph_bfs(source, target, parent):
    visited = [False] * vertices
    queue = deque()
    queue.append(source)
    visited[source] = True

    while queue:
        current = queue.popleft()
        for adj, cp in adj_table[current].items():
            if cp and not visited[adj]:
                queue.append(adj)
                visited[adj] = True
                parent[adj] = current

    return True if visited[target] else False


def graphFordFulkerson(source, sink):
    parent = [-1] * vertices
    max_flow = 0

    while graph_bfs(source, sink, parent):
        path_flow = float('inf')

        bk_1 = sink
        while bk_1 is not source:
            path_flow = min(path_flow, adj_table[parent[bk_1]][bk_1])
            bk_1 = parent[bk_1]

        max_flow += path_flow

        bk_2 = sink
        while bk_2 is not source:
            parent_bk_2 = parent[bk_2]
            assert parent_bk_2 != -1
            adj_table[parent_bk_2].setdefault(bk_2, 0)
            adj_table[bk_2].setdefault(parent_bk_2, 0)

            
            adj_table[parent_bk_2][bk_2] -= path_flow
            adj_table[bk_2][parent_bk_2] += path_flow
            bk_2 = parent[bk_2]

    return max_flow


def generate_adj_table(v_table):
    for each in v_table:
        source, target, cp = map(int, each)
        init_adj_table[source][target] = cp

    return init_adj_table


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices, edges = map(int, _input[0].split())
    v_info = map(lambda x: x.split(), _input[1:])

    init_adj_table = [dict() for _ in range(vertices)]
    adj_table = generate_adj_table(v_info)
    ans = graphFordFulkerson(source=0, sink=vertices - 1)
    print(ans)