結果

問題 No.421 しろくろチョコレート
ユーザー 👑 rin204
提出日時 2022-07-12 19:00:22
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 148 ms / 2,000 ms
コード長 2,411 bytes
コンパイル時間 490 ms
コンパイル使用メモリ 82,560 KB
実行使用メモリ 79,532 KB
最終ジャッジ日時 2024-06-23 16:53:52
合計ジャッジ時間 8,136 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 65
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque

class Dinic:
    def __init__(self, n):
        self.n = n
        self.links = [[] for _ in range(n)]
        self.depth = None
        self.progress = None
 
    def add_link(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):
        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'))

n, m = map(int, input().split())
S = [input() for _ in range(n)]

directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
G = Dinic(n * m + 2)
s = n * m
t = s + 1
f = lambda i, j: i * m + j
b = 0
w = 0
for i in range(n):
    for j in range(m):
        if S[i][j] == ".":
            continue
        p = f(i, j)
        if S[i][j] == "w":
            w += 1
            G.add_link(s, p, 1)
            for di, dj in directions:
                ni = i + di
                nj = j + dj
                if ni == -1 or ni == n or nj == -1 or nj == m:
                    continue
                G.add_link(p, f(ni, nj), 1)
        else:
            b += 1
            G.add_link(p, t, 1)

fl = G.max_flow(s, t)
ans = fl * 100
b -= fl
w -= fl
ans += min(b, w) * 10
ans += max(b, w) - min(b, w)
print(ans)
0