結果

問題 No.957 植林
ユーザー zundamo-ti
提出日時 2021-03-02 06:13:51
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 2,398 bytes
コンパイル時間 170 ms
コンパイル使用メモリ 82,176 KB
実行使用メモリ 182,732 KB
最終ジャッジ日時 2024-10-03 01:33:05
合計ジャッジ時間 14,853 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 9 WA * 2 RE * 4 TLE * 1 -- * 29
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
readline = sys.stdin.readline
INF = float('inf')

class Dinic:
    def __init__(self, n):
        self.n = n
        self.links = [[] for _ in range(n)]
        self.depth = None
        self.progress = None
 
    def add_edge(self, _from, to, cap):
        self.links[_from].append([cap, to, len(self.links[to])])
        self.links[to].append([0, _from, len(self.links[_from]) - 1])
 
    def bfs(self, s):
        from collections import deque

        depth = [-1] * self.n
        depth[s] = 0
        q = deque([s])
        while q:
            v = q.popleft()
            for cap, to, rev in self.links[v]:
                if cap > 0 and depth[to] < 0:
                    depth[to] = depth[v] + 1
                    q.append(to)
        self.depth = depth
 
    def dfs(self, v, t, flow):
        if v == t:
            return flow
        links_v = self.links[v]
        for i in range(self.progress[v], len(links_v)):
            self.progress[v] = i
            cap, to, rev = link = links_v[i]
            if cap == 0 or self.depth[v] >= self.depth[to]:
                continue
            d = self.dfs(to, t, min(flow, cap))
            if d == 0:
                continue
            link[0] -= d
            self.links[to][rev][0] += d
            return d
        return 0
 
    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            if self.depth[t] < 0:
                return flow
            self.progress = [0] * self.n
            current_flow = self.dfs(s, t, float('inf'))
            while current_flow > 0:
                flow += current_flow
                current_flow = self.dfs(s, t, float('inf'))

def main():
    H, W = map(int, readline().split())
    G = tuple(tuple(map(int, readline().split())) for _ in range(H))
    R = tuple(map(int, readline().split()))
    C = tuple(map(int, readline().split()))
    
    V = H * W + H + W + 2
    dinic = Dinic(V)
    s, t = V - 2, V - 1
    add = dinic.add_edge
    for h in range(H):
        for w in range(W):
            v = W * h + w
            add(s, v, G[h][w])
            add(v, h + H * W, INF)
            add(v, w + H * W + W, INF)
    for h in range(H):
        add(h + H * W, t, R[h])
    for w in range(W):
        add(w + H * W + W, t, C[w])
    flow = dinic.max_flow(s, t)
    print(sum(R) + sum(C) - flow)

if __name__ == "__main__":
    main()
0