Problem:


  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

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|$

$u_0\;v_0\;c_0$

$u_1\;v_1\;c_1$

:

$u_{|E|-1}\;v_{|E|-1}\;c_{|E|-1}$

$|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



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


Sample output:
3

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
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] * v_num
    queue = deque()
    queue.appendleft(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] * v_num
    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)

            # print(bk_2, parent_bk_2, path_flow, bk_1, parent[bk_1], parent, adj_table)
            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(_edges):
    for edge in _edges:
        source, target, cp = map(int, edge)
        init_adj_table[source][target] = cp

    return init_adj_table


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

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
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] * v_num
    queue = deque()
    queue.appendleft(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] * v_num
    max_flow = 0

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

        bk_1 = sink
        while bk_1 is not source:
            parent_bk_1 = parent[bk_1]
            assert parent_bk_1 != -1
            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)

            # print(bk_2, parent_bk_2, path_flow, bk_1, parent[bk_1], parent, adj_table)
            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(_edges):
    for edge in _edges:
        source, target, cp = map(int, edge)
        init_adj_table[source][target] = cp

    return init_adj_table


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

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
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] * v_num
    queue = deque()
    queue.appendleft(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 graph_FordFulkerson(source, sink):
    parent = [-1] * v_num
    max_flow = 0

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

        bk_1 = sink
        while bk_1 is not source:
            parent_bk_1 = parent[bk_1]
            assert parent_bk_1 != -1
            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)

            # print(bk_2, parent_bk_2, path_flow, bk_1, parent[bk_1], parent, adj_table)
            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(_edges):
    for edge in _edges:
        source, target, cp = map(int, edge)
        init_adj_table[source].setdefault(target, cp)

    return init_adj_table


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

    init_adj_table = [dict() for _ in range(v_num)]
    adj_table = generate_adj_table(edges)
    ans = graph_FordFulkerson(source=0, sink=v_num - 1)
    print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
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 bfs(source, target, parent):
    queue = deque()
    queue.appendleft(source)
    visited = [False] * v_num
    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 graph_FordFulkerson(source, sink):
    parent = [-1] * v_num
    max_flow = 0

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

        bk_1 = sink
        while bk_1 != source:
            parent_bk_1 = parent[bk_1]
            assert parent_bk_1 != -1
            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]
            assert parent_bk_2 != -1
            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


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

    adj_table = tuple(dict() for _ in range(v_num))
    for edge in edges:
        s, t, c = map(int, edge)
        adj_table[s][t] = c

    print(graph_FordFulkerson(source=0, sink=v_num - 1))

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
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 bfs(source, target, parent):
    queue = deque()
    queue.appendleft(source)
    visited = [False] * v_num
    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 graph_FordFulkerson(source, sink):
    parent = [-1] * v_num
    max_flow = 0

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

        bk_1 = sink
        while bk_1 != source:
            parent_bk_1 = parent[bk_1]
            assert parent_bk_1 != -1
            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]
            assert parent_bk_2 != -1
            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


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

    adj_table = tuple(dict() for _ in range(v_num))
    for edge in edges:
        s, t, cp = map(int, edge)
        adj_table[s][t] = cp

    ans = graph_FordFulkerson(source=0, sink=v_num - 1)
    print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
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 bfs(source, target, parent):
    visited = [False] * v_num
    queue = deque()
    queue.appendleft(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 graph_FordFulkerson(source, sink):
    parent = [-1] * v_num
    max_flow = 0

    while bfs(source, sink, parent):
        path_flow = float('inf')
        
        # 1st backward traversal
        bk_1 = sink
        while bk_1 != source:
            parent_bk_1 = parent[bk_1]
            assert parent_bk_1 != -1
            path_flow = min(path_flow, adj_table[parent_bk_1][bk_1])
            bk_1 = parent[bk_1]

        max_flow += path_flow

        # 2nd backward traversal
        bk_2 = sink
        while bk_2 != source:
            parent_bk_2 = parent[bk_2]
            assert parent_bk_2 != -1
            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


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

    adj_table = tuple(dict() for _ in range(v_num))
    for edge in edges:
        s, t, c = map(int, edge)
        adj_table[s][t] = c

    print(graph_FordFulkerson(source=0, sink=v_num - 1))

Submission status: Accepted

Solution code:
# Acceptance of input

import sys

file_input = sys.stdin

V, E = map(int, file_input.readline().split())

adj_mat = [[0] * V for i in range(V)]

for line in file_input:
    u, v, c = map(int, line.split())
    adj_mat[u][v] = c

# Ford???Fulkerson algorithm

import collections

# BFS for residual capacity network
def bfs(start, goal, parent):
    unvisited = [True] * V
    queue = collections.deque()
    queue.append(start)
    unvisited[start] = False
    while queue:
        u = queue.popleft()
        for v, flow in enumerate(adj_mat[u]):
            if unvisited[v] and (flow > 0):
                queue.append(v)
                unvisited[v] = False
                parent[v] = u
    return not unvisited[goal]

def ford_fulkerson(source, sink):
    parent = [None] * V
    max_flow = 0
    while bfs(source, sink, parent):
        aug_path_flow = 10000
        v = sink
        while (v != source):
            aug_path_flow = min(aug_path_flow, adj_mat[parent[v]][v])
            v = parent[v]
        max_flow += aug_path_flow
        v = sink
        while (v != source):
            u = parent[v]
            adj_mat[u][v] -= aug_path_flow
            adj_mat[v][u] += aug_path_flow
            v = u
    return max_flow

# output
print(ford_fulkerson(0, V - 1))

Submission status: Accepted

Solution code:
# Acceptance of input

import sys

file_input = sys.stdin

V, E = map(int, file_input.readline().split())

adj_mat = [[0] * V for i in range(V)]

for line in file_input:
    u, v, c = map(int, line.split())
    adj_mat[u][v] = c

# Ford???Fulkerson algorithm

import collections

# BFS for residual capacity network
def bfs(start, goal, parent):
    unvisited = [True] * V
    queue = collections.deque()
    queue.append(start)
    unvisited[start] = False
    while queue:
        u = queue.popleft()
        for v, flow in enumerate(adj_mat[u]):
            if unvisited[v] and (flow > 0):
                queue.append(v)
                unvisited[v] = False
                parent[v] = u
                if v == goal:
                    return True

def ford_fulkerson(source, sink):
    parent = [None] * V
    max_flow = 0
    while bfs(source, sink, parent):
        aug_path_flow = 10000
        v = sink
        while (v != source):
            aug_path_flow = min(aug_path_flow, adj_mat[parent[v]][v])
            v = parent[v]
        max_flow += aug_path_flow
        v = sink
        while (v != source):
            u = parent[v]
            adj_mat[u][v] -= aug_path_flow
            adj_mat[v][u] += aug_path_flow
            v = u
    return max_flow

# output
print(ford_fulkerson(0, V - 1))

Submission status: Accepted

Solution code:
# Acceptance of input

import sys

file_input = sys.stdin

V, E = map(int, file_input.readline().split())

adj_mat = [[0] * V for i in range(V)]

for line in file_input:
    u, v, c = map(int, line.split())
    adj_mat[u][v] = c

# Ford???Fulkerson algorithm

import collections

# BFS for residual capacity network
def bfs(start, goal, parent):
    flow = [0] * V
    queue = collections.deque()
    queue.append(start)
    flow[start] = 10000
    while queue:
        u = queue.popleft()
        for v, r_capacity in enumerate(adj_mat[u]):
            if not flow[v] and (r_capacity > 0):
                queue.append(v)
                flow[v] = min(flow[u], r_capacity)
                parent[v] = u
    return flow[goal]

def ford_fulkerson(source, sink):
    max_flow = 0
    while True:
        parent = [None] * V
        aug_path_flow = bfs(source, sink, parent)
        if aug_path_flow:
            max_flow += aug_path_flow
            v = sink
            while (v != source):
                u = parent[v]
                adj_mat[u][v] -= aug_path_flow
                adj_mat[v][u] += aug_path_flow
                v = u
        else:
            break
    return max_flow

# output
print(ford_fulkerson(0, V - 1))

Submission status: Accepted

Solution code:
# Acceptance of input

import sys

file_input = sys.stdin

V, E = map(int, file_input.readline().split())

adj_mat = [[0] * V for i in range(V)]

for line in file_input:
    u, v, c = map(int, line.split())
    adj_mat[u][v] = c

# Ford???Fulkerson algorithm

import collections

# BFS for residual capacity network
def bfs(start, goal, parent):
    flow = [0] * V
    queue = collections.deque()
    queue.append(start)
    flow[start] = 10000
    while queue:
        u = queue.popleft()
        for v, r_capacity in enumerate(adj_mat[u]):
            if not flow[v] and (r_capacity > 0):
                queue.append(v)
                flow[v] = min(flow[u], r_capacity)
                parent[v] = u
                if v == goal:
                    return flow[goal]

def ford_fulkerson(source, sink):
    max_flow = 0
    while True:
        parent = [None] * V
        aug_path_flow = bfs(source, sink, parent)
        if aug_path_flow:
            max_flow += aug_path_flow
            v = sink
            while (v != source):
                u = parent[v]
                adj_mat[u][v] -= aug_path_flow
                adj_mat[v][u] += aug_path_flow
                v = u
        else:
            break
    return max_flow

# output
print(ford_fulkerson(0, V - 1))

Submission status: Accepted

Solution code:
# Acceptance of input

import sys

file_input = sys.stdin

V, E = map(int, file_input.readline().split())

adj_mat = [[0] * V for i in range(V)]

for line in file_input:
    u, v, c = map(int, line.split())
    adj_mat[u][v] = c

# Ford???Fulkerson algorithm

import collections

# BFS for residual capacity network
def bfs(start, goal, parent):
    unvisited = [True] * V
    queue = collections.deque()
    queue.append(start)
    unvisited[start] = False
    while queue:
        u = queue.popleft()
        for v, r_capacity in enumerate(adj_mat[u]):
            if unvisited[v] and (r_capacity > 0):
                queue.append(v)
                unvisited[v] = False
                parent[v] = u
                if v == goal:
                    return not unvisited[goal]

def ford_fulkerson(source, sink):
    parent = [None] * V
    max_flow = 0
    while bfs(source, sink, parent):
        aug_path_flow = 10000
        v = sink
        while (v != source):
            aug_path_flow = min(aug_path_flow, adj_mat[parent[v]][v])
            v = parent[v]
        max_flow += aug_path_flow
        v = sink
        while (v != source):
            u = parent[v]
            adj_mat[u][v] -= aug_path_flow
            adj_mat[v][u] += aug_path_flow
            v = u
    return max_flow

# output
print(ford_fulkerson(0, V - 1))

Submission status: Accepted

Solution code:
# Acceptance of input

import sys

file_input = sys.stdin

V, E = map(int, file_input.readline().split())

adj_mat = [[0] * V for i in range(V)]

for line in file_input:
    u, v, c = map(int, line.split())
    adj_mat[u][v] = c

# Ford???Fulkerson method

import collections

# BFS for residual capacity network
def bfs(start, goal, parent):
    unvisited = [True] * V
    queue = collections.deque()
    queue.append(start)
    unvisited[start] = False
    while queue:
        u = queue.popleft()
        for v, r_capacity in enumerate(adj_mat[u]):
            if unvisited[v] and (r_capacity > 0):
                queue.append(v)
                unvisited[v] = False
                parent[v] = u
                if v == goal:
                    return not unvisited[goal]

def ford_fulkerson(source, sink):
    parent = [None] * V
    max_flow = 0
    while bfs(source, sink, parent):
        aug_path_flow = 10000
        v = sink
        while (v != source):
            aug_path_flow = min(aug_path_flow, adj_mat[parent[v]][v])
            v = parent[v]
        max_flow += aug_path_flow
        v = sink
        while (v != source):
            u = parent[v]
            adj_mat[u][v] -= aug_path_flow
            adj_mat[v][u] += aug_path_flow
            v = u
    return max_flow

# output
print(ford_fulkerson(0, V - 1))

Submission status: Accepted

Solution code:
# Acceptance of input

import sys

file_input = sys.stdin

V, E = map(int, file_input.readline().split())

adj_mat = [[0] * V for i in range(V)]

for line in file_input:
    u, v, c = map(int, line.split())
    adj_mat[u][v] = c

# Dinic's algorithm

import collections

# BFS for residual capacity network to construct level graph
def bfs(start, goal, parent):
    level = [V] * V
    unvisited = [True] * V
    queue = collections.deque()
    queue.append(start)
    level[start] = 0
    unvisited[start] = False
    while queue:
        u = queue.popleft()
        next_level = level[u] + 1
        for v, r_capacity in enumerate(adj_mat[u]):
            if (level[v] >= next_level) and (r_capacity > 0):
                level[v] = next_level
                parent[v].append(u)
                if unvisited[v]:
                    queue.append(v)
                    unvisited[v] = False
    return level[goal]

# DFS for level graph and construct blocking flow
def dfs(goal, path, parent, blocking_flow):
    v = path[-1]
    if v == goal:
        aug_path_flow = 10000
        for x, y in zip(path[1:], path[:-1]):
            aug_path_flow = min(aug_path_flow, adj_mat[x][y])
        for x, y in zip(path[1:], path[:-1]):
            adj_mat[x][y] -= aug_path_flow
            adj_mat[y][x] += aug_path_flow
        blocking_flow[0] += aug_path_flow
    else:
        for u in parent[v]:
            path.append(u)
            dfs(goal, path, parent, blocking_flow)
            path.pop()

def dinic(source, sink):
    max_flow = 0
    parent = [[] for i in range(V)]
    while bfs(source, sink, parent) != V:
        blocking_flow = [0]
        path = [sink]
        # search in reverse direction from sink
        dfs(source, path, parent, blocking_flow)
        max_flow += blocking_flow[0]
        parent = [[] for i in range(V)]
    return max_flow

# output
print(dinic(0, V - 1))

Submission status: Accepted

Solution code:
def bfs():
    visited = [False] * nv
    visited[0] = True
    q = [0]

    while q:
        u = q.pop(0)
        for i, w in enumerate(adj[u]):
            if not visited[i] and w > 0:
                q.append(i)
                visited[i] = True
                parents[i] = u

    return True if visited[nv - 1] else False

def maxf():
    max_flow = 0
    while bfs():
        flow = float('inf')
        c = nv - 1

        while c:
            flow = min(flow, adj[parents[c]][c])
            c = parents[c]

        max_flow += flow
        v = nv - 1

        while v:
            u = parents[v]
            adj[u][v] -= flow
            adj[v][u] += flow
            v = parents[v]

    return max_flow

nv, ne = map(int, input().split(' '))
adj = [[0] * nv for _ in range(nv)]
parents = [None] * nv

for _ in range(ne):
    s, t, w = map(int, input().split(' '))
    adj[s][t] = w

print(maxf())

Submission status: Accepted

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

def makeG(n):
    return [[] for _ in xrange(n)]

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

def dfs(G,v,t,f,used):
    if v==t: return f
    used[v]=True
    for i in xrange(len(G[v])):
        e=G[v][i]
        if not used[e.to] and e.cap>0:
            d=dfs(G,e.to,t,min(f,e.cap),used)
            if d>0:
                e.cap-=d
                G[e.to][e.rev].cap+=d
                return d
    return 0
    
def max_flow(G,n,s,t):
    flow=0
    while True:
        used=[False]*n
        f=dfs(G,s,t,float("inf"),used)
        if f==0: return flow
        flow+=f

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

Submission status: Accepted

Solution code:
import collections
class Dinic:
    def __init__(self, n):
        self.n = n
        self.g = [[] for i in xrange(n)]
    def add_edge(self, fr, to, cap):
        self.g[fr].append([to, cap, len(self.g[to])])
        self.g[to].append([fr, 0, len(self.g[fr])-1])
    def add_multi_edge(self, v1, v2, cap1, cap2):
        self.g[v1].append([v2, cap1, len(self.g[v2])])
        self.g[v2].append([v1, cap2, len(self.g[v1])-1])
    def bfs(self, s):
        level = [-1]*self.n
        deq = collections.deque()
        level[s] = 0
        deq.append(s)
        while deq:
            v = deq.popleft()
            for e in self.g[v]:
                if e[1]>0 and level[e[0]]<0:
                    level[e[0]] = level[v] + 1
                    deq.append(e[0])
        self.level = level
    def dfs(self, v, t, f):
        if v==t: return f
        es = self.g[v]
        level = self.level
        for i in xrange(self.it[v], len(self.g[v])):
            e = es[i]
            if e[1]>0 and level[v]<level[e[0]]:
                d = self.dfs(e[0], t, min(f, e[1]))
                if d>0:
                    e[1] -= d
                    self.g[e[0]][e[2]][1] += d
                    self.it[v] = i
                    return d
        self.it[v] = len(self.g[v])
        return 0
    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            if self.level[t]<0: break
            self.it = [0]*self.n
            while True:
                f = self.dfs(s, t, 10**9+7)
                if f>0:
                    flow += f
                else:
                    break
        return flow
V, E = map(int, raw_input().split())
dinic = Dinic(V)
for i in xrange(E):
    u, v, c = map(int, raw_input().split())
    dinic.add_edge(u, v, c)
print dinic.max_flow(0, V-1)

Submission status: Accepted

Solution code:
def main():
    nvertices, nedges = map(int, input().split())
    edges = [[0 for i in range(nvertices)] for j in range(nvertices)]
    for i in range(nedges):
        u, v, c = map(int, input().split())
        edges[u][v] = c

    ans = 0
    while True:
        val = bfs(0, nvertices - 1, edges)
        if val is None:
            break
        f, path = val
        ans += f
        for i in range(1, len(path)):
            u, v = path[i - 1], path[i]
            edges[u][v] -= f
            edges[v][u] += f

    print(ans)


def bfs(s, t, edges):
    visited = [False] * len(edges)
    INF = float('inf')
    que = [(s, INF, [s])]
    while que:
        u, f, path = que.pop()
        visited[u] = True
        if u == t:
            return (f, path)

        for v in range(len(edges)):
            if visited[v]:
                continue
            if edges[u][v] == 0:
                continue
            p = path[:]
            p.append(v)
            que.insert(0, (v, min(f, edges[u][v]), p))

    return None


main()

Submission status: Accepted

Solution code:
def main():
    nvertices, nedges = map(int, input().split())
    edges = [[0 for i in range(nvertices)] for j in range(nvertices)]
    for i in range(nedges):
        u, v, c = map(int, input().split())
        edges[u][v] = c

    INF = float('inf')
    ans = 0
    while True:
        parents = bfs(0, nvertices - 1, edges)
        if parents is None:
            break
        parent, child = parents[nvertices - 1], nvertices - 1
        f = INF
        while parent != -1:
            f = min(f, edges[parent][child])
            parent, child = parents[parent], parent

        ans += f
        parent, child = parents[nvertices - 1], nvertices - 1
        while parent != -1:
            edges[parent][child] -= f
            edges[child][parent] += f
            parent, child = parents[parent], parent

    print(ans)


def bfs(s, t, edges):
    visited = [False] * len(edges)
    que = [s]
    parents = [-1] * len(edges)
    while que:
        u = que.pop(0)
        visited[u] = True
        if u == t:
            return parents

        for v in range(len(edges)):
            if not visited[v] and edges[u][v] > 0:
                parents[v] = u
                que.append(v)

    return None


main()

Submission status: Accepted

Solution code:
def main():
    nvertices, nedges = map(int, input().split())
    adj = [[0 for i in range(nvertices)] for j in range(nvertices)]
    for i in range(nedges):
        u, v, c = map(int, input().split())
        adj[u][v] = c

    INF = float('inf')
    ans = 0
    while True:
        parents = bfs(0, nvertices - 1, adj)
        if parents is None:
            break
        v = nvertices - 1
        f = INF
        while parents[v] != -1:
            f = min(f, adj[parents[v]][v])
            v = parents[v]

        ans += f
        v = nvertices - 1
        while parents[v] != -1:
            adj[parents[v]][v] -= f
            adj[v][parents[v]] += f
            v = parents[v]

    print(ans)


def bfs(s, t, adj):
    visited = [False] * len(adj)
    que = [s]
    parents = [-1] * len(adj)
    while que:
        u = que.pop(0)
        visited[u] = True
        if u == t:
            return parents

        for v in range(len(adj)):
            if not visited[v] and adj[u][v] > 0:
                parents[v] = u
                que.append(v)

    return None


main()

Submission status: Accepted

Solution code:
def main():
    nvertices, nedges = map(int, input().split())
    adj = [[0] * nvertices for j in range(nvertices)]
    for i in range(nedges):
        u, v, c = map(int, input().split())
        adj[u][v] = c

    INF = float('inf')
    ans = 0
    while True:
        parents = bfs(0, nvertices - 1, adj)
        if parents is None:
            break
        v = nvertices - 1
        f = INF
        while parents[v] != -1:
            f = min(f, adj[parents[v]][v])
            v = parents[v]

        ans += f
        v = nvertices - 1
        while v != 0:
            u = parents[v]
            adj[u][v] -= f
            adj[v][u] += f
            v = u

    print(ans)


def bfs(s, t, adj):
    nvertices = len(adj)
    visited = [False] * nvertices
    visited[0] = True
    que = [s]
    parents = [-1] * nvertices
    while que:
        u = que.pop(0)
        if u == t:
            return parents

        for v in range(len(adj)):
            if not visited[v] and adj[u][v] > 0:
                parents[v] = u
                visited[v] = True
                que.append(v)

    return None


main()