結果

問題 No.1479 Matrix Eraser
ユーザー 草苺奶昔草苺奶昔
提出日時 2023-03-14 02:25:10
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 434 ms / 3,000 ms
コード長 3,747 bytes
コンパイル時間 238 ms
コンパイル使用メモリ 82,048 KB
実行使用メモリ 136,192 KB
最終ジャッジ日時 2024-09-18 07:52:20
合計ジャッジ時間 11,143 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 66 ms
67,072 KB
testcase_01 AC 67 ms
67,584 KB
testcase_02 AC 66 ms
67,968 KB
testcase_03 AC 63 ms
67,968 KB
testcase_04 AC 64 ms
67,584 KB
testcase_05 AC 66 ms
67,584 KB
testcase_06 AC 66 ms
67,584 KB
testcase_07 AC 163 ms
86,016 KB
testcase_08 AC 194 ms
92,160 KB
testcase_09 AC 258 ms
102,812 KB
testcase_10 AC 382 ms
118,680 KB
testcase_11 AC 277 ms
109,184 KB
testcase_12 AC 163 ms
88,320 KB
testcase_13 AC 180 ms
92,160 KB
testcase_14 AC 169 ms
88,816 KB
testcase_15 AC 113 ms
80,256 KB
testcase_16 AC 179 ms
90,112 KB
testcase_17 AC 417 ms
131,840 KB
testcase_18 AC 427 ms
131,968 KB
testcase_19 AC 413 ms
131,968 KB
testcase_20 AC 421 ms
132,224 KB
testcase_21 AC 406 ms
131,840 KB
testcase_22 AC 418 ms
131,840 KB
testcase_23 AC 406 ms
131,712 KB
testcase_24 AC 434 ms
131,840 KB
testcase_25 AC 409 ms
131,968 KB
testcase_26 AC 427 ms
131,968 KB
testcase_27 AC 226 ms
90,112 KB
testcase_28 AC 229 ms
90,112 KB
testcase_29 AC 225 ms
89,984 KB
testcase_30 AC 225 ms
90,240 KB
testcase_31 AC 232 ms
90,624 KB
testcase_32 AC 164 ms
102,400 KB
testcase_33 AC 166 ms
102,400 KB
testcase_34 AC 160 ms
102,400 KB
testcase_35 AC 160 ms
102,272 KB
testcase_36 AC 162 ms
102,400 KB
testcase_37 AC 117 ms
97,408 KB
testcase_38 AC 237 ms
91,776 KB
testcase_39 AC 381 ms
136,192 KB
testcase_40 AC 69 ms
67,712 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque
from typing import List, Optional, Tuple


class Hungarian:
    """
    軽量化Dinic法
    ref : https://snuke.hatenablog.com/entry/2019/05/07/013609
    """

    __slots__ = ("_row", "_col", "_to")

    def __init__(self, graph: Optional[List[List[int]]] = None):
        self._row = 0
        self._col = 0
        self._to = [[]]
        if graph is not None:
            colors, ok = isBipartite(len(graph), graph)
            if not ok:
                raise ValueError("graph is not bipartite")
            for u, vs in enumerate(graph):
                if colors[u] == 0:
                    for v in vs:
                        if colors[v] == 1:
                            self.addEdge(u, v)

    def addEdge(self, u: int, v: int) -> None:
        """男孩u和女孩v连边"""
        if self._col <= v:
            self._col = v + 1
        if self._row <= u:
            self._row = u + 1
            while len(self._to) <= u:
                self._to.append([])
        self._to[u].append(v)

    def work(self) -> List[Tuple[int, int]]:
        """返回最大匹配"""
        n, m, to = self._row, self._col, self._to
        pre = [-1] * n
        root = [-1] * n
        p = [-1] * n
        q = [-1] * m
        upd = True
        while upd:
            upd = False
            s = []
            s_front = 0
            for i in range(n):
                if p[i] == -1:
                    root[i] = i
                    s.append(i)
            while s_front < len(s):
                v = s[s_front]
                s_front += 1
                if p[root[v]] != -1:
                    continue
                for u in to[v]:
                    if q[u] == -1:
                        while u != -1:
                            q[u] = v
                            p[v], u = u, p[v]
                            v = pre[v]
                        upd = True
                        break
                    u = q[u]
                    if pre[u] != -1:
                        continue
                    pre[u] = v
                    root[u] = root[v]
                    s.append(u)
            if upd:
                for i in range(n):
                    pre[i] = -1
                    root[i] = -1
        return [(v, p[v]) for v in range(n) if p[v] != -1]


def isBipartite(n: int, adjList: List[List[int]]) -> Tuple[List[int], bool]:
    """二分图检测 bfs染色"""

    def bfs(start: int) -> bool:
        colors[start] = 0
        queue = deque([start])
        while queue:
            cur = queue.popleft()
            for next in adjList[cur]:
                if colors[next] == -1:
                    colors[next] = colors[cur] ^ 1
                    queue.append(next)
                elif colors[next] == colors[cur]:
                    return False
        return True

    colors = [-1] * n
    for i in range(n):
        if colors[i] == -1 and not bfs(i):
            return [], False
    return colors, True

from collections import defaultdict
from typing import List


def solve(grid: List[List[int]]) -> int:
    ROW, COL = len(grid), len(grid[0])
    mp = defaultdict(list)
    for i in range(ROW):
        for j in range(COL):
            mp[grid[i][j]].append((i, j))

    res = 0
    for v, edges in mp.items():
        if v == 0:
            continue
        H = Hungarian()
        id1, id2 = dict(), dict()
        for u, v in edges:
            id1.setdefault(u, len(id1))
            id2.setdefault(v, len(id2))
            H.addEdge(id1[u], id2[v])
        res += len(H.work())

    return res


if __name__ == "__main__":
    n, m = map(int, input().split())
    grid = [list(map(int, input().split())) for _ in range(n)]
    print(solve(grid))
0