結果
問題 |
No.421 しろくろチョコレート
|
ユーザー |
![]() |
提出日時 | 2025-03-31 17:32:40 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 133 ms / 2,000 ms |
コード長 | 3,028 bytes |
コンパイル時間 | 239 ms |
コンパイル使用メモリ | 82,488 KB |
実行使用メモリ | 78,760 KB |
最終ジャッジ日時 | 2025-03-31 17:33:40 |
合計ジャッジ時間 | 6,451 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 65 |
ソースコード
import sys from collections import deque, defaultdict def main(): input = sys.stdin.read().split() idx = 0 N = int(input[idx]); idx += 1 M = int(input[idx]); idx += 1 grid = [] for _ in range(N): grid.append(input[idx]) idx += 1 total_white = 0 total_black = 0 white_nodes = [] black_nodes = [] for i in range(N): for j in range(M): c = grid[i][j] if c == 'w': total_white += 1 white_nodes.append((i, j)) elif c == 'b': total_black += 1 black_nodes.append((i, j)) method3 = 0 if white_nodes and black_nodes: white_id = {(i, j): idx for idx, (i, j) in enumerate(white_nodes)} black_id = {(i, j): idx for idx, (i, j) in enumerate(black_nodes)} graph = defaultdict(list) for idx_w, (i, j) in enumerate(white_nodes): for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: ni, nj = i + dx, j + dy if 0 <= ni < N and 0 <= nj < M: if grid[ni][nj] == 'b': if (ni, nj) in black_id: graph[idx_w].append(black_id[(ni, nj)]) # Hopcroft-Karp algorithm implementation pair_U = [None] * len(white_nodes) pair_V = [None] * len(black_nodes) dist = [0] * len(white_nodes) def bfs(): queue = deque() for u in range(len(white_nodes)): if pair_U[u] is None: dist[u] = 0 queue.append(u) else: dist[u] = float('inf') dist_null = float('inf') while queue: u = queue.popleft() if dist[u] < dist_null: for v in graph[u]: if pair_V[v] is None: dist_null = dist[u] + 1 elif dist[pair_V[v]] == float('inf'): dist[pair_V[v]] = dist[u] + 1 queue.append(pair_V[v]) return dist_null != float('inf') def dfs(u): for v in graph[u]: if pair_V[v] is None or (dist[pair_V[v]] == dist[u] + 1 and dfs(pair_V[v])): pair_U[u] = v pair_V[v] = u return True dist[u] = float('inf') return False method3 = 0 while bfs(): for u in range(len(white_nodes)): if pair_U[u] is None: if dfs(u): method3 += 1 remaining_white = total_white - method3 remaining_black = total_black - method3 method2 = min(remaining_white, remaining_black) method1 = (remaining_white - method2) + (remaining_black - method2) total = 100 * method3 + 10 * method2 + method1 print(total) if __name__ == '__main__': main()