Problem:


Score : 100 points

Problem Statement

You are given a grid of N rows and M columns. The square at the i-th row and j-th column will be denoted as (i,j).
A nonnegative integer A_{i,j} is written for each square (i,j).

You choose some of the squares so that each row and column contains at most K chosen squares.
Under this constraint, calculate the maximum value of the sum of the integers written on the chosen squares.
Additionally, calculate a way to choose squares that acheives the maximum.

Constraints

1 \leq N \leq 50

1 \leq K \leq N

0 \leq A_{i,j} \leq 10^9

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N K
A_{1,1} A_{1,2} \cdots A_{1,N}
A_{2,1} A_{2,2} \cdots A_{2,N}
\vdots
A_{N,1} A_{N,2} \cdots A_{N,N}

Output

On the first line, print the maximum value of the sum of the integers written on the chosen squares.

On the next N lines, print a way that achieves the maximum.

Precisely, output the strings t_1,t_2,\cdots,t_N, that satisfies t_{i,j}=X if you choose (i,j) and t_{i,j}=. otherwise.

You may print any way to choose squares that maximizes the sum.

Sample Input 1

3 1
5 3 2
1 4 8
7 6 9

Sample Output 1

19
X..
..X
.X.

Sample Input 2

3 2
10 10 1
10 10 1
1 1 10

Sample Output 2

50
XX.
XX.
..X



Sample input:
3 1
5 3 2
1 4 8
7 6 9


Sample output:
19
X..
..X
.X.

Submission status: Accepted

Solution code:
import heapq

class mcf_graph:



    def __init__(self, n):
        self.n = n
        self.pos = []
        self.g = [[] for _ in range(n)]


    def add_edge(self, from_, to, cap, cost):
        # assert 0 <= from_ < self.n
        # assert 0 <= to < self.n
        m = len(self.pos)
        self.pos.append((from_, len(self.g[from_])))
        self.g[from_].append(self.__class__._edge(to, len(self.g[to]), cap, cost))
        self.g[to].append(self.__class__._edge(from_, len(self.g[from_]) - 1, 0, -cost))
        return m


    class edge:
        __slots__ = ["from_", "to", "cap", "flow", "cost"]
        def __init__(self, from_, to, cap, flow, cost):
            self.from_ = from_
            self.to = to
            self.cap = cap
            self.flow = flow
            self.cost = cost


    def get_edge(self, i):
        _e = self.g[self.pos[i][0]][self.pos[i][1]]
        _re = self.g[_e.to][_e.rev]
        return self.__class__.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost)


    def edges(self):
        ret = []
        for i in range(len(self.pos)):
            _e = self.g[self.pos[i][0]][self.pos[i][1]]
            _re = self.g[_e.to][_e.rev]
            ret.append(self.__class__.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost))
        return ret


    def slope(self, s, t, flow_limit=float('inf')):
        # assert 0 <= s < self.n
        # assert 0 <= t < self.n
        # assert s != t
        
        dual = [0] * self.n
        dist = [float('inf')] * self.n
        pv = [-1] * self.n
        pe = [-1] * self.n
        vis = [False] * self.n

        def _dual_ref():
            nonlocal dual, dist, pv, pe, vis
            dist = [float('inf')] * self.n
            pv = [-1] * self.n
            pe = [-1] * self.n
            vis = [False] * self.n

            que = [(0, s)]
            dist[s] = 0
            while que:
                _, v = heapq.heappop(que)
                if vis[v]:
                    continue
                vis[v] = True
                if v == t:
                    break
                for i in range(len(self.g[v])):
                    e = self.g[v][i]
                    if vis[e.to] or e.cap == 0:
                        continue
                    cost = e.cost - dual[e.to] + dual[v]
                    if dist[e.to] > dist[v] + cost:
                        dist[e.to] = dist[v] + cost
                        pv[e.to] = v
                        pe[e.to] = i
                        heapq.heappush(que, (dist[e.to], e.to))
            if not vis[t]:
                return False

            for v in range(self.n):
                if not vis[v]:
                    continue
                dual[v] -= dist[t] - dist[v]
            
            return True

        flow = 0
        cost = 0
        prev_cost = -1
        result = [(flow, cost)]
        while flow < flow_limit:
            if not _dual_ref():
                break
            c = flow_limit - flow
            v = t
            while v != s:
                c = min(c, self.g[pv[v]][pe[v]].cap)
                v = pv[v]
            v = t
            while v != s:
                e = self.g[pv[v]][pe[v]]
                e.cap -= c
                self.g[v][e.rev].cap += c
                v = pv[v]
            d = -dual[s]
            flow += c
            cost += c * d
            if prev_cost == d:
                result.pop()
            result.append((flow, cost))
            prev_cost = cost
        return result


    def flow(self, s, t, flow_limit=float('inf')):
        return self.slope(s, t, flow_limit)[-1]

    
    class _edge:
        __slots__ = ["to", "rev", "cap", "cost"]
        def __init__(self, to, rev, cap, cost):
            self.to = to
            self.rev = rev
            self.cap = cap
            self.cost = cost


BIG = 10 ** 9

import sys
input = sys.stdin.readline

N, K = map(int, input().split())

g = mcf_graph(2 * N + 2)
s = 2 * N
t = 2 * N + 1

g.add_edge(s, t, N * K, BIG)
for i in range(N):
    g.add_edge(s, i, K, 0)
    g.add_edge(N + i, t, K, 0)

for i in range(N):
    As = map(int, input().split())
    for j, A in enumerate(As):
        g.add_edge(i, N + j, 1, BIG - A)

result = g.flow(s, t, N * K)

print(N * K * BIG - result[1])

grid = [['.' for _ in range(N)] for _ in range(N)]
edges = g.edges()
for e in edges:
    if e.from_ == s or e.to == t or e.flow == 0:
        continue
    grid[e.from_][e.to - N] = 'X'

for row in grid:
    print(''.join(row))

Submission status: Accepted

Solution code:
import heapq

class mcf_graph:


    def __init__(self, n):
        self.n = n
        self.pos = []
        self.g = [[] for _ in range(n)]


    def add_edge(self, from_, to, cap, cost):
        # assert 0 <= from_ < self.n
        # assert 0 <= to < self.n
        m = len(self.pos)
        self.pos.append((from_, len(self.g[from_])))
        self.g[from_].append(self.__class__._edge(to, len(self.g[to]), cap, cost))
        self.g[to].append(self.__class__._edge(from_, len(self.g[from_]) - 1, 0, -cost))
        return m


    class edge:
        def __init__(self, from_, to, cap, flow, cost):
            self.from_ = from_
            self.to = to
            self.cap = cap
            self.flow = flow
            self.cost = cost


    def get_edge(self, i):
        _e = self.g[self.pos[i][0]][self.pos[i][1]]
        _re = self.g[_e.to][_e.rev]
        return self.__class__.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost)


    def edges(self):
        ret = []
        for i in range(len(self.pos)):
            _e = self.g[self.pos[i][0]][self.pos[i][1]]
            _re = self.g[_e.to][_e.rev]
            ret.append(self.__class__.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost))
        return ret


    def slope(self, s, t, flow_limit=float('inf')):
        # assert 0 <= s < self.n
        # assert 0 <= t < self.n
        # assert s != t
        
        dual = [0] * self.n
        dist = [float('inf')] * self.n
        pv = [-1] * self.n
        pe = [-1] * self.n
        vis = [False] * self.n

        def _dual_ref():
            nonlocal dual, dist, pv, pe, vis
            dist = [float('inf')] * self.n
            pv = [-1] * self.n
            pe = [-1] * self.n
            vis = [False] * self.n

            que = [(0, s)]
            dist[s] = 0
            while que:
                _, v = heapq.heappop(que)
                if vis[v]:
                    continue
                vis[v] = True
                if v == t:
                    break
                for i in range(len(self.g[v])):
                    e = self.g[v][i]
                    if vis[e.to] or e.cap == 0:
                        continue
                    cost = e.cost - dual[e.to] + dual[v]
                    if dist[e.to] > dist[v] + cost:
                        dist[e.to] = dist[v] + cost
                        pv[e.to] = v
                        pe[e.to] = i
                        heapq.heappush(que, (dist[e.to], e.to))
            if not vis[t]:
                return False

            for v in range(self.n):
                if not vis[v]:
                    continue
                dual[v] -= dist[t] - dist[v]
            
            return True

        flow = 0
        cost = 0
        prev_cost = -1
        result = [(flow, cost)]
        while flow < flow_limit:
            if not _dual_ref():
                break
            c = flow_limit - flow
            v = t
            while v != s:
                c = min(c, self.g[pv[v]][pe[v]].cap)
                v = pv[v]
            v = t
            while v != s:
                e = self.g[pv[v]][pe[v]]
                e.cap -= c
                self.g[v][e.rev].cap += c
                v = pv[v]
            d = -dual[s]
            flow += c
            cost += c * d
            if prev_cost == d:
                result.pop()
            result.append((flow, cost))
            prev_cost = cost
        return result


    def flow(self, s, t, flow_limit=float('inf')):
        return self.slope(s, t, flow_limit)[-1]

    
    class _edge:
        def __init__(self, to, rev, cap, cost):
            self.to = to
            self.rev = rev
            self.cap = cap
            self.cost = cost


BIG = 10 ** 9

import sys
input = sys.stdin.readline

N, K = map(int, input().split())

g = mcf_graph(2 * N + 2)
s = 2 * N
t = 2 * N + 1

g.add_edge(s, t, N * K, BIG)
for i in range(N):
    g.add_edge(s, i, K, 0)
    g.add_edge(N + i, t, K, 0)

for i in range(N):
    As = map(int, input().split())
    for j, A in enumerate(As):
        g.add_edge(i, N + j, 1, BIG - A)

result = g.flow(s, t, N * K)

print(N * K * BIG - result[1])

grid = [['.' for _ in range(N)] for _ in range(N)]
edges = g.edges()
for e in edges:
    if e.from_ == s or e.to == t or e.flow == 0:
        continue
    grid[e.from_][e.to - N] = 'X'

for row in grid:
    print(''.join(row))

Submission status: Accepted

Solution code:
import heapq

class mcf_graph:

    
    __slots__ = ["n", "pos", "g"]


    def __init__(self, n):
        self.n = n
        self.pos = []
        self.g = [[] for _ in range(n)]


    def add_edge(self, from_, to, cap, cost):
        assert 0 <= from_ < self.n
        assert 0 <= to < self.n
        m = len(self.pos)
        self.pos.append((from_, len(self.g[from_])))
        self.g[from_].append(self.__class__._edge(to, len(self.g[to]), cap, cost))
        self.g[to].append(self.__class__._edge(from_, len(self.g[from_]) - 1, 0, -cost))
        return m


    class edge:
        def __init__(self, from_, to, cap, flow, cost):
            self.from_ = from_
            self.to = to
            self.cap = cap
            self.flow = flow
            self.cost = cost


    def get_edge(self, i):
        _e = self.g[self.pos[i][0]][self.pos[i][1]]
        _re = self.g[_e.to][_e.rev]
        return self.__class__.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost)


    def edges(self):
        ret = []
        for i in range(len(self.pos)):
            _e = self.g[self.pos[i][0]][self.pos[i][1]]
            _re = self.g[_e.to][_e.rev]
            ret.append(self.__class__.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost))
        return ret


    def slope(self, s, t, flow_limit=float('inf')):
        assert 0 <= s < self.n
        assert 0 <= t < self.n
        assert s != t
        
        dual = [0] * self.n
        dist = [float('inf')] * self.n
        pv = [-1] * self.n
        pe = [-1] * self.n
        vis = [False] * self.n

        def _dual_ref():
            nonlocal dual, dist, pv, pe, vis
            dist = [float('inf')] * self.n
            pv = [-1] * self.n
            pe = [-1] * self.n
            vis = [False] * self.n

            que = [(0, s)]
            dist[s] = 0
            while que:
                _, v = heapq.heappop(que)
                if vis[v]:
                    continue
                vis[v] = True
                if v == t:
                    break
                for i in range(len(self.g[v])):
                    e = self.g[v][i]
                    if vis[e.to] or e.cap == 0:
                        continue
                    cost = e.cost - dual[e.to] + dual[v]
                    if dist[e.to] > dist[v] + cost:
                        dist[e.to] = dist[v] + cost
                        pv[e.to] = v
                        pe[e.to] = i
                        heapq.heappush(que, (dist[e.to], e.to))
            if not vis[t]:
                return False

            for v in range(self.n):
                if not vis[v]:
                    continue
                dual[v] -= dist[t] - dist[v]
            
            return True

        flow = 0
        cost = 0
        prev_cost = -1
        result = [(flow, cost)]
        while flow < flow_limit:
            if not _dual_ref():
                break
            c = flow_limit - flow
            v = t
            while v != s:
                c = min(c, self.g[pv[v]][pe[v]].cap)
                v = pv[v]
            v = t
            while v != s:
                e = self.g[pv[v]][pe[v]]
                e.cap -= c
                self.g[v][e.rev].cap += c
                v = pv[v]
            d = -dual[s]
            flow += c
            cost += c * d
            if prev_cost == d:
                result.pop()
            result.append((flow, cost))
            prev_cost = cost
        return result


    def flow(self, s, t, flow_limit=float('inf')):
        return self.slope(s, t, flow_limit)[-1]

    
    class _edge:
        def __init__(self, to, rev, cap, cost):
            self.to = to
            self.rev = rev
            self.cap = cap
            self.cost = cost


BIG = 10 ** 9

import sys
input = sys.stdin.readline

N, K = map(int, input().split())

g = mcf_graph(2 * N + 2)
s = 2 * N
t = 2 * N + 1

g.add_edge(s, t, N * K, BIG)
for i in range(N):
    g.add_edge(s, i, K, 0)
    g.add_edge(N + i, t, K, 0)

for i in range(N):
    As = map(int, input().split())
    for j, A in enumerate(As):
        g.add_edge(i, N + j, 1, BIG - A)

result = g.flow(s, t, N * K)

print(N * K * BIG - result[1])

grid = [['.' for _ in range(N)] for _ in range(N)]
edges = g.edges()
for e in edges:
    if e.from_ == s or e.to == t or e.flow == 0:
        continue
    grid[e.from_][e.to - N] = 'X'

for row in grid:
    print(''.join(row))

Submission status: Accepted

Solution code:
import heapq

class mcf_graph:


    def __init__(self, n):
        self.n = n
        self.pos = []
        self.g = [[] for _ in range(n)]


    def add_edge(self, from_, to, cap, cost):
        assert 0 <= from_ < self.n
        assert 0 <= to < self.n
        m = len(self.pos)
        self.pos.append((from_, len(self.g[from_])))
        self.g[from_].append(self.__class__._edge(to, len(self.g[to]), cap, cost))
        self.g[to].append(self.__class__._edge(from_, len(self.g[from_]) - 1, 0, -cost))
        return m


    class edge:
        def __init__(self, from_, to, cap, flow, cost):
            self.from_ = from_
            self.to = to
            self.cap = cap
            self.flow = flow
            self.cost = cost


    def get_edge(self, i):
        _e = self.g[self.pos[i][0]][self.pos[i][1]]
        _re = self.g[_e.to][_e.rev]
        return self.__class__.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost)


    def edges(self):
        ret = []
        for i in range(len(self.pos)):
            _e = self.g[self.pos[i][0]][self.pos[i][1]]
            _re = self.g[_e.to][_e.rev]
            ret.append(self.__class__.edge(self.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap, _e.cost))
        return ret


    def slope(self, s, t, flow_limit=float('inf')):
        assert 0 <= s < self.n
        assert 0 <= t < self.n
        assert s != t
        
        dual = [0] * self.n
        dist = [float('inf')] * self.n
        pv = [-1] * self.n
        pe = [-1] * self.n
        vis = [False] * self.n

        def _dual_ref():
            nonlocal dual, dist, pv, pe, vis
            dist = [float('inf')] * self.n
            pv = [-1] * self.n
            pe = [-1] * self.n
            vis = [False] * self.n

            que = [(0, s)]
            dist[s] = 0
            while que:
                _, v = heapq.heappop(que)
                if vis[v]:
                    continue
                vis[v] = True
                if v == t:
                    break
                for i in range(len(self.g[v])):
                    e = self.g[v][i]
                    if vis[e.to] or e.cap == 0:
                        continue
                    cost = e.cost - dual[e.to] + dual[v]
                    if dist[e.to] > dist[v] + cost:
                        dist[e.to] = dist[v] + cost
                        pv[e.to] = v
                        pe[e.to] = i
                        heapq.heappush(que, (dist[e.to], e.to))
            if not vis[t]:
                return False

            for v in range(self.n):
                if not vis[v]:
                    continue
                dual[v] -= dist[t] - dist[v]
            
            return True

        flow = 0
        cost = 0
        prev_cost = -1
        result = [(flow, cost)]
        while flow < flow_limit:
            if not _dual_ref():
                break
            c = flow_limit - flow
            v = t
            while v != s:
                c = min(c, self.g[pv[v]][pe[v]].cap)
                v = pv[v]
            v = t
            while v != s:
                e = self.g[pv[v]][pe[v]]
                e.cap -= c
                self.g[v][e.rev].cap += c
                v = pv[v]
            d = -dual[s]
            flow += c
            cost += c * d
            if prev_cost == d:
                result.pop()
            result.append((flow, cost))
            prev_cost = cost
        return result


    def flow(self, s, t, flow_limit=float('inf')):
        return self.slope(s, t, flow_limit)[-1]

    
    class _edge:
        def __init__(self, to, rev, cap, cost):
            self.to = to
            self.rev = rev
            self.cap = cap
            self.cost = cost


BIG = 10 ** 9

import sys
input = sys.stdin.readline

N, K = map(int, input().split())

g = mcf_graph(2 * N + 2)
s = 2 * N
t = 2 * N + 1

g.add_edge(s, t, N * K, BIG)
for i in range(N):
    g.add_edge(s, i, K, 0)
    g.add_edge(N + i, t, K, 0)

for i in range(N):
    As = map(int, input().split())
    for j, A in enumerate(As):
        g.add_edge(i, N + j, 1, BIG - A)

result = g.flow(s, t, N * K)

print(N * K * BIG - result[1])

grid = [['.' for _ in range(N)] for _ in range(N)]
edges = g.edges()
for e in edges:
    if e.from_ == s or e.to == t or e.flow == 0:
        continue
    grid[e.from_][e.to - N] = 'X'

for row in grid:
    print(''.join(row))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from heapq import heappop, heappush, heapify
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7


# MinCostFlow
# derived: https://atcoder.jp/contests/practice2/submissions/16726003

class MinCostFlow():
    def __init__(self, n):
        self.n = n
        self.graph = [[] for _ in range(n)]
        self.pos = []

    def add_edge(self, fr, to, cap, cost):
        #assert 0 <= fr < self.n
        #assert 0 <= to < self.n
        m = len(self.pos)
        self.pos.append((fr, len(self.graph[fr])))
        self.graph[fr].append([to, len(self.graph[to]), cap, cost])
        self.graph[to].append([fr, len(self.graph[fr]) - 1, 0, -cost])
        return m

    def get_edge(self, idx):
        #assert 0 <= idx < len(self.pos)
        to, rev, cap, cost = self.graph[self.pos[idx][0]][self.pos[idx][1]]
        _rev_to, _rev_rev, rev_cap, _rev_cost = self.graph[to][rev]
        return self.pos[idx][0], to, cap + rev_cap, rev_cap, cost

    def edges(self):
        for i in range(len(self.pos)):
            yield self.get_edge(i)

    def dual_ref(self, s, t):
        dist = [2**63 - 1] * self.n
        dist[s] = 0
        vis = [0] * self.n
        self.pv = [-1] * self.n
        self.pe = [-1] * self.n
        queue = []
        heappush(queue, (0, s))
        while queue:
            k, v = heappop(queue)
            if vis[v]:
                continue
            vis[v] = True
            if v == t:
                break
            for i in range(len(self.graph[v])):
                to, _rev, cap, cost = self.graph[v][i]
                if vis[to] or cap == 0:
                    continue
                cost += self.dual[v] - self.dual[to]
                if dist[to] - dist[v] > cost:
                    dist[to] = dist[v] + cost
                    self.pv[to] = v
                    self.pe[to] = i
                    heappush(queue, (dist[to], to))
        if not vis[t]:
            return False
        for v in range(self.n):
            if not vis[v]:
                continue
            self.dual[v] -= dist[t] - dist[v]
        return True

    def flow(self, s, t):
        return self.flow_with_limit(s, t, 2**63 - 1)

    def flow_with_limit(self, s, t, limit):
        return self.slope_with_limit(s, t, limit)[-1]

    def slope(self, s, t):
        return self.slope_with_limit(s, t, 2**63 - 1)

    def slope_with_limit(self, s, t, limit):
        #assert 0 <= s < self.n
        #assert 0 <= t < self.n
        #assert s != t
        flow = 0
        cost = 0
        prev_cost = -1
        res = [(flow, cost)]
        self.dual = [0] * self.n
        while flow < limit:
            if not self.dual_ref(s, t):
                break
            c = limit - flow
            v = t
            while v != s:
                c = min(c, self.graph[self.pv[v]][self.pe[v]][2])
                v = self.pv[v]
            v = t
            while v != s:
                _to, rev, _cap, _ = self.graph[self.pv[v]][self.pe[v]]
                self.graph[self.pv[v]][self.pe[v]][2] -= c
                self.graph[v][rev][2] += c
                v = self.pv[v]
            d = -self.dual[s]
            flow += c
            cost += c * d
            if prev_cost == d:
                res.pop()
            res.append((flow, cost))
            prev_cost = cost
        return res


def debug(*x):
    print(*x, file=sys.stderr)


def solve(N, data, K):
    mcf = MinCostFlow(2 * N + 2)
    start = 2 * N
    goal = 2 * N + 1
    mcf.add_edge(start, goal, N * K, INF)

    for i in range(N):
        mcf.add_edge(start, i, K, 0)
        mcf.add_edge(i + N, goal, K, 0)
        for j in range(N):
            mcf.add_edge(i, j + N, 1, INF - data[i][j])

    print(N * K * INF - mcf.flow_with_limit(start, goal, N * K)[1])

    ret = [['.' for j in range(N)] for i in range(N)]

    for frm, to, _cap, flow, _cost in mcf.edges():
        if flow == 0 or frm == start or to == goal:
            continue
        ret[frm][to - N] = 'X'

    for r in ret:
        print(''.join(r))


def main():
    # parse input
    N, K = map(int, input().split())
    data = []
    for _i in range(N):
        data.append(list(map(int, input().split())))

    solve(N, data, K)


# tests
T1 = """
3 1
5 3 2
1 4 8
7 6 9
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
19
X..
..X
.X.
"""

T2 = """
3 2
10 10 1
10 10 1
1 1 10
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
50
XX.
XX.
..X
"""


def _test():
    import doctest
    doctest.testmod()
    g = globals()
    for k in sorted(g):
        if k.startswith("TEST_"):
            doctest.run_docstring_examples(g[k], g, name=k)


def as_input(s):
    "use in test, use given string as input file"
    import io
    f = io.StringIO(s.strip())
    g = globals()
    g["input"] = lambda: bytes(f.readline(), "ascii")
    g["read"] = lambda: bytes(f.read(), "ascii")


input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read

if sys.argv[-1] == "-t":
    print("testing")
    _test()
    sys.exit()

main()

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
MAP=[list(map(int,input().split())) for i in range(N)]

start = 2*N+1
goal = 2*N+2
V=2*N+5

EDGE=[[[0,0] for j in range(V)] for i in range(V)]

# 0 ～ N : 縦
# N+1 ～　2*N : 横
# 2*N+1 : start
# 2*N+2 : goal

for i in range(N):
    EDGE[start][i]=[K,0]
    EDGE[N+i][goal]=[K,0]
    
for i in range(N):
    for j in range(N):
        EDGE[i][N+j]=[1,10**9-MAP[i][j]]
        EDGE[N+j][i]=[0,-(10**9-MAP[i][j])]

EDGE[start][goal]=[float("inf"),10**9]

BACK=[-1]*V
LA=0
 
import heapq
 
for flow in range(K*N):
    ANS=[float("inf")]*V
    Q=[(0,start)]
    ANS[start]=0
 
    while Q:
        time,fr=heapq.heappop(Q)
        if time>ANS[fr]:
            continue

        for to in range(V):
            c,d = EDGE[fr][to]
            if c>0 and ANS[to]>ANS[fr]+d:
                ANS[to]=ANS[fr]+d
                BACK[to]=fr
                heapq.heappush(Q,(ANS[to],to))

    LA+=ANS[goal]
 
    NOW=goal
    while NOW!=start:
        fr=BACK[NOW]
        EDGE[fr][NOW][0]-=1
        EDGE[NOW][fr][0]+=1

        NOW=fr
 
print(K*N*10**9-LA)
ALIST=[["."]*N for i in range(N)]

for i in range(N):
    for j in range(N):
        if EDGE[i][N+j][0]==0:
            ALIST[i][j]="X"

for alist in ALIST:
    print("".join(alist))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
MAP=[list(map(int,input().split())) for i in range(N)]

start = 2*N+1
goal = 2*N+2
V=2*N+5

EDGE=[[[0,0] for j in range(V)] for i in range(V)]

# 0 ～ N : 縦
# N+1 ～　2*N : 横
# 2*N+1 : start
# 2*N+2 : goal



for i in range(N):
    EDGE[start][i]=[K,0]
    EDGE[N+i][goal]=[K,0]
    
for i in range(N):
    for j in range(N):
        EDGE[i][N+j]=[1,-MAP[i][j]]
        EDGE[N+j][i]=[0,MAP[i][j]]

EDGE[start][goal]=[float("inf"),0]


BACK=[-1]*V
LA=0

for flow in range(K*N):
    ANS=[float("inf")]*V
    ANS[start]=0

    for rep in range(V):
        flag=0
        for fr in range(V):
            for to in range(V):             
                c,d=EDGE[fr][to]
                if c>0 and ANS[to]>ANS[fr]+d:
                    ANS[to]=ANS[fr]+d
                    flag=1
                    BACK[to]=fr
        if flag==0:
            break

    if ANS[goal]==0:
        break
 
    LA+=ANS[goal]
 
    NOW=goal
    while NOW!=start:
        fr=BACK[NOW]
        EDGE[fr][NOW][0]-=1
        EDGE[NOW][fr][0]+=1

        NOW=fr
 
print(-LA)
ALIST=[["."]*N for i in range(N)]

for i in range(N):
    for j in range(N):
        if EDGE[i][N+j][0]==0:
            ALIST[i][j]="X"

for alist in ALIST:
    print("".join(alist))

Submission status: Accepted

Solution code:
mod = 1000000007
eps = 10**-9
val_max = 10**9


def main():
    import sys
    input = sys.stdin.readline
    from heapq import heappush, heappop

    # 負辺未対応
    class Mincostflow():
        def __init__(self, N):
            self.N = N
            self.adj = [[] for _ in range(N + 1)]
            self.inf = 1 << 60

        def add_edge(self, fr, to, cap, cost):
            # [to, cap, cost, rev]
            forward = [to, cap, cost, None]
            backward = forward[3] = [fr, 0, -cost, forward]
            self.adj[fr].append(forward)
            self.adj[to].append(backward)

        def flow(self, s, t, f):
            N = self.N
            adj = self.adj
            inf = self.inf

            res = 0
            H = [0] * (N + 1)
            prev_v = [0] * (N + 1)
            prev_e = [None] * (N + 1)

            dist0 = [inf] * (N + 1)
            dist = [inf] * (N + 1)

            while f:
                dist[:] = dist0
                dist[s] = 0
                pq = [(0, s)]
                while pq:
                    d, v = heappop(pq)
                    if d > dist[v]:
                        continue
                    r0 = dist[v] + H[v]
                    for e in adj[v]:
                        u, cap, cost, _ = e
                        if cap > 0 and r0 + cost - H[u] < dist[u]:
                            dist[u] = r = r0 + cost - H[u]
                            heappush(pq, (r, u))
                            prev_v[u] = v
                            prev_e[u] = e

                # flow f doesn't exist
                if dist[t] == inf:
                    return None

                for i in range(1, N + 1):
                    H[i] += dist[i]

                g = f
                v = t
                while v != s:
                    g = min(g, prev_e[v][1])
                    v = prev_v[v]
                f -= g
                res += g * H[t]
                v = t
                while v != s:
                    e = prev_e[v]
                    e[1] -= g
                    e[-1][1] += g
                    v = prev_v[v]

            return res

    N, K = map(int, input().split())
    grid = []
    for _ in range(N):
        grid.append(list(map(int, input().split())))

    s = 2*N+1
    t = 2*N+2
    mcf = Mincostflow(N*2 + 2)
    mcf.add_edge(s, t, N*K, val_max)
    for i in range(1, N+1):
        mcf.add_edge(s, i, K, 0)
        mcf.add_edge(i+N, t, K, 0)
    for i in range(1, N+1):
        for j in range(N+1, 2*N+1):
            mcf.add_edge(i, j, 1, val_max - grid[i-1][j-1-N])

    print(val_max * N * K - mcf.flow(s, t, N*K))
    ans = [["."] * N for _ in range(N)]
    for i in range(1, N+1):
        for j, cap, cost, _ in mcf.adj[i]:
            if cap == 0:
                ans[i-1][j-1-N] = "X"
    for i in range(N):
        print("".join(ans[i]))


if __name__ == '__main__':
    main()