Cod sursa(job #2560483)

Utilizator andru47Stefanescu Andru andru47 Data 28 februarie 2020 02:29:07
Problema Flux maxim Scor 50
Compilator py Status done
Runda Arhiva educationala Marime 2.2 kb
import math
import queue
from collections import defaultdict


class Graph:
    def __init__(self):
        self.edges = defaultdict(list)
        self.flux = defaultdict(list)
        self.capacity = defaultdict(list)
    def add_n_m(self, n, m):
        self.n = n
        self.m = m
        for i in range(n):
            self.flux[i + 1] = [0] * (n + 1)
            self.capacity[i + 1] = [0] * (n + 1)
    def add_edge(self, x, y, cap):
        self.capacity[x][y] = cap
        self.edges[x].append(y)
        self.edges[y].append(x)
    def edmonds(self):
        q = queue.Queue()
        q.put(int(1))
        from_where = [-1] * (self.n + 1)
        from_where[1] = 0
        while not q.empty():
            top = q.get()
            for it in self.edges[top]:
                if from_where[it] == -1 and self.capacity[top][it] > self.flux[top][it]:
                    from_where[it] = top
                    q.put(it)
        return (from_where, from_where[self.n] != -1)
    def ford(self):
        ret = 0
        while True:
            res = self.edmonds()
            from_where = res[0]
            if not res[1]:
                return ret
            it = self.n
            miny = math.inf
            while it != 1:
                miny = min(miny, self.capacity[from_where[it]][it] - self.flux[from_where[it]][it])
                it = from_where[it]
            ret += miny
            it = self.n
            while it != 1:
                self.flux[from_where[it]][it] += miny
                self.flux[it][from_where[it]] -= miny
                it = from_where[it]
def parse(str, i):
    while i < len(str) and (str[i] < '0' or str[i] > '9'):
        i = i + 1
    num = 0
    str2 = ""
    while i < len(str) and (str[i] >= '0' and str[i] <= '9'):
        str2 += str[i]
        i = i + 1
    num = int(str2)
    return (i, num)

def read(graph):
    f = open("maxflow.in", "r")
    str = f.read()
    i = 0
    (i , n) = parse(str, i)
    (i, m) = parse(str, i)
    graph.add_n_m(n, m)
    for _ in range(m):
        (i, x) = parse(str, i)
        (i, y) = parse(str, i)
        (i, c) = parse(str, i)
        graph.add_edge(x, y, c)
graph = Graph()
read(graph)
g = open("maxflow.out", "w")
g.write(str(graph.ford()))