結果

問題 No.421 しろくろチョコレート
ユーザー rlangevin
提出日時 2023-07-20 12:24:12
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 174 ms / 2,000 ms
コード長 2,388 bytes
コンパイル時間 211 ms
コンパイル使用メモリ 82,048 KB
実行使用メモリ 80,112 KB
最終ジャッジ日時 2024-09-20 08:56:48
合計ジャッジ時間 7,991 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 65
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import *
class Maxflow:
    def __init__(self, N):
        self.N = N
        self.G = [[] for i in range(N)]
        
    def add_edge(self, u, v, c):
        self.G[u].append([v, c, len(self.G[v])])
        self.G[v].append([u, 0, len(self.G[u]) - 1])
        
    def bfs(self, s):
        D = [-1] * self.N
        D[s] = 0
        Q = deque()
        Q.append(s)
        while Q:
            u = Q.popleft()
            for next, cap, _ in self.G[u]:
                if cap > 0 and D[next] < 0:
                    D[next] = D[u] + 1
                    Q.append(next)
        return D
    
    def dfs(self, v, t, f, removed, D):
        if v == t:
            return f
        
        while removed[v] < len(self.G[v]):
            next, cap, rev = self.G[v][removed[v]]
            if cap > 0 and D[v] < D[next]:
                flow = self.dfs(next, t, min(f, cap), removed, D)
                if flow > 0:
                    self.G[v][removed[v]][1] -= flow
                    self.G[next][rev][1] += flow
                    return flow
                
            removed[v] += 1
        return 0
    
    def calc_max_flow(self, s, t):
        flow = 0
        while True:
            D = self.bfs(s)
            if D[t] < 0:
                return flow
            removed = [0] * self.N
            while True:
                f = self.dfs(s, t, 1e10, removed, D)
                if f == 0:
                    break
                flow += f


N, M = map(int, input().split())
S = []
w, b = 0, 0
for i in range(N):
    S.append(list(input()))
    w += S[i].count("w")
    b += S[i].count("b")

start = N * M
goal = start + 1
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
G = Maxflow(N * M + 2)
for i in range(N):
    for j in range(M):
        if S[i][j] == ".":
            continue
        if (i + j) % 2 == 0:
            G.add_edge(i * M + j, goal, 1)
            continue

        G.add_edge(start, i * M + j, 1)
        for k in range(4):
            x = i + dx[k]
            y = j + dy[k]
            if x < 0 or x > N - 1 or y < 0 or y > M - 1:
                continue
            if S[x][y] == ".":
                continue
            if S[i][j] != S[x][y]:
                G.add_edge(i * M + j, x * M + y, 1)

ans = 0
mf = G.calc_max_flow(start, goal)
ans += mf * 100
b, w = b - mf, w - mf
ans += min(b, w) * 10 + max(b, w) - min(b, w)
print(ans)
0