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).
Some of the squares contain an object. All the remaining squares are empty.
The state of the grid is represented by strings S_1,S_2,\cdots,S_N. The square (i,j) contains an object if S_{i,j}= # and is empty if S_{i,j}= ..

Consider placing 1 \times 2 tiles on the grid. Tiles can be placed vertically or horizontally to cover two adjacent empty squares.
Tiles must not stick out of the grid, and no two different tiles may intersect. Tiles cannot occupy the square with an object.

Calculate the maximum number of tiles that can be placed and any configulation that acheives the maximum.

Constraints

1 \leq N \leq 100

1 \leq M \leq 100

S_i is a string with length M consists of # and ..

Input

Input is given from Standard Input in the following format:

N M
S_1
S_2
\vdots
S_N

Output

On the first line, print the maximum number of tiles that can be placed.

On the next N lines, print a configulation that achieves the maximum.
Precisely, output the strings t_1,t_2,\cdots,t_N constructed by the following way.

t_i is initialized to S_i.

For each (i,j), if there is a tile that occupies (i,j) and (i+1,j), change t_{i,j}:=v, t_{i+1,j}:=^.

For each (i,j), if there is a tile that occupies (i,j) and (i,j+1), change t_{i,j}:=>, t_{i,j+1}:=<.

See samples for further information.

You may print any configulation that maximizes the number of tiles.

Sample Input 1

3 3
#..
..#
...

Sample Output 1

3
#><
vv#
^^.

The following output is also treated as a correct answer.

3
#><
v.#
^><



Sample input:
3 3
#..
..#
...


Sample output:
3
#><
vv#
^^.

Submission status: Wrong Answer

Solution code:
from typing import NamedTuple, Optional, List


class MaxFlow:
    class Edge(NamedTuple):
        src: int
        dst: int
        cap: int
        flow: int

    class _Edge:
        dst: int
        cap: int
        rev: Optional['MaxFlow._Edge']

        def __init__(self, dst: int, cap: int):
            self.dst = dst
            self.cap = cap
            self.rev = None

    def __init__(self, n: int):
        self._n = n
        self._g: List[List[MaxFlow._Edge]] = [[] for _ in range(n)]
        self._edges: List[MaxFlow._Edge] = []

    def add_edge(self, src: int, dst: int, cap: int) -> int:
        assert 0 <= src < self._n
        assert 0 <= dst < self._n
        assert 0 <= cap
        m = len(self._edges)
        e = MaxFlow._Edge(dst, cap)
        re = MaxFlow._Edge(src, 0)
        e.rev = re
        re.rev = e
        self._g[src].append(e)
        self._g[dst].append(re)
        self._edges.append(e)
        return m

    def get_edge(self, i: int) -> Edge:
        assert 0 <= i < len(self._edges)
        e = self._edges[i]
        re = e.rev
        return MaxFlow.Edge(
            re.dst,
            e.dst,
            e.cap + re.cap,
            re.cap
        )

    def edges(self) -> List[Edge]:
        return [self.get_edge(i) for i in range(len(self._edges))]

    def change_edge(self, i: int, new_cap: int, new_flow: int):
        assert 0 <= i < len(self._edges)
        assert 0 <= new_flow <= new_cap
        e = self._edges[i]
        e.cap = new_cap - new_flow
        e.rev.cap = new_flow

    def flow(self, s: int, t: int, flow_limit: Optional[int] = None) -> int:
        assert 0 <= s < self._n
        assert 0 <= t < self._n
        assert s != t
        if flow_limit is None:
            flow_limit = sum(e.cap for e in self._g[s])

        current_edge = [0] * self._n
        level = [0] * self._n
        buf: List[int] = []
        edge_stack: List[MaxFlow._Edge] = []

        def fill(arr: List[int], value: int):
            for i in range(len(arr)):
                arr[i] = value

        def bfs() -> bool:
            fill(level, self._n)
            queue = buf
            queue.clear()
            q_front = 0
            queue.append(s)
            level[s] = 0
            while q_front < len(queue):
                v = queue[q_front]
                print(v)
                q_front += 1
                next_level = level[v] + 1
                for e in self._g[v]:
                    if e.cap == 0 or level[e.dst] <= next_level:
                        continue
                    level[e.dst] = next_level
                    if e.dst == t:
                        return True
                    queue.append(e.dst)
            return False

        def dfs(lim) -> int:
            stack = buf
            stack.clear()
            stack.append(t)
            edge_stack.clear()
            while stack:
                v = stack[-1]
                if v == s:
                    flow = min(lim, min(e.cap for e in edge_stack))
                    for e in edge_stack:
                        e.cap -= flow
                        e.rev.cap += flow
                    return flow
                next_level = level[v] - 1
                while current_edge[v] < len(self._g[v]):
                    e = self._g[v][current_edge[v]]
                    re = e.rev
                    if level[e.dst] != next_level or re.cap == 0:
                        current_edge[v] += 1
                        continue
                    stack.append(e.dst)
                    edge_stack.append(re)
                    break
                else:
                    stack.pop()
                    if edge_stack:
                        edge_stack.pop()
                    level[v] = self._n
            return 0

        flow = 0
        while flow < flow_limit:
            if not bfs():
                break
            fill(current_edge, 0)
            while flow < flow_limit:
                f = dfs(flow_limit - flow)
                flow += f
                if f == 0:
                    break
        return flow


# https://atcoder.jp/contests/practice2/tasks/practice2_d
def main() -> None:
    import sys
    n, m = map(int, sys.stdin.readline().split())
    s = n * m
    t = s + 1
    g = MaxFlow(t + 1)
    grid = [list(sys.stdin.readline().strip()) for _ in range(n)]

    def enc(i: int, j: int) -> int:
        return i * m + j

    def dec(v: int) -> (int, int):
        return v // m, v % m

    for i in range(n):
        for j in range(m):
            if grid[i][j] == '#':
                continue
            if (i + j) % 2 == 0:
                g.add_edge(s, enc(i, j), 1)
            else:
                g.add_edge(enc(i, j), t, 1)

    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    for i in range(n):
        for j in range(m):
            if (i + j) % 2 == 1 or grid[i][j] == '#':
                continue
            for direction in range(4):
                ii = i + dx[direction]
                jj = j + dy[direction]
                if 0 <= ii < n and 0 <= jj < m and grid[ii][jj] == '.':
                    print(enc(i, j), enc(ii, jj))
                    g.add_edge(enc(i, j), enc(ii, jj), 1)

    print(g.flow(s, t))
    for e in g.edges():
        if e.src == s or e.dst == t or e.flow == 0:
            continue
        (i, j) = dec(e.src)
        (ii, jj) = dec(e.dst)
        if i == ii + 1:
            grid[ii][jj] = 'v'
            grid[i][j] = '^'
        elif j == jj + 1:
            grid[ii][jj] = '>'
            grid[i][j] = '<'
        elif i == ii - 1:
            grid[i][j] = 'v'
            grid[ii][jj] = '^'
        else:
            grid[i][j] = '>'
            grid[ii][jj] = '<'

    for s in grid:
        print("".join(s))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter
import queue

import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


class Dinic:
    def __init__(self, v):
        self.V = v
        self.G = [list() for _ in range(v)]
        self.level = [0 for _ in range(v)]
        self.iter = [0 for _ in range(v)]
        self.pos = []

    def add_edge(self, from_, to, cap):
        self.pos.append((from_, len(self.G[from_])))
        # to: 行き先, cap: 容量, rev: 反対側の辺
        # 0           1          2
        self.G[from_].append([to, cap, len(self.G[to])])
        self.G[to].append([from_, 0, len(self.G[from_])-1])


    def edges(self):
        es = []
        for f, t in self.pos:
            e = self.G[f][t]
            re = self.G[e[0]][e[2]]
            # from, to, cap, flow
            e = [f, e[0], e[1] + re[1], re[1]]
            es.append(e)
        return es

    # sからの最短距離をbfsで計算
    def bfs(self, s):
        self.level = [-1 for _ in range(self.V)]
        self.level[s] = 0
        que = queue.Queue()
        que.put(s)
        while not que.empty():
            v = que.get()
            for i in range(len(self.G[v])):
                e = self.G[v][i]
                if e[1] > 0 and self.level[e[0]] < 0:
                    self.level[e[0]] = self.level[v] + 1
                    que.put(e[0])

    # 増加バスをdfsで探す
    def dfs(self, v, t, f):
        if v == t:
            return f
        for i in range(self.iter[v], len(self.G[v])):
            self.iter[v] = i
            e = self.G[v][i]
            if e[1] > 0 and self.level[v] < self.level[e[0]]:
                d = self.dfs(e[0], t, min(f, e[1]))
                if d > 0:
                    e[1] -= d
                    self.G[e[0]][e[2]][1] += d
                    return d

        return 0

    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            # bfsで到達不可
            if self.level[t] < 0:
                return flow
            self.iter = [0 for _ in range(self.V)]
            f = self.dfs(s, t, INF)
            while f > 0:
                flow += f
                f = self.dfs(s, t, INF)


@mt
def slv(N, M, S):
    S = [list(s) for s in S]
    g = Dinic(N*M+2)
    s = N*M
    t = s + 1

    for i in range(N):
        for j in range(M):
            if S[i][j] == '#':
                continue
            v = i*M + j
            if (i + j )%2 == 0:
                g.add_edge(s, v, 1)
            else:
                g.add_edge(v, t, 1)



    # for i in range(N):
    #     for j in range(M):
    #         if S[i][j] == '#':
    #             continue
    #         if (i+j) % 2 == 1:
    #             continue
    #         v0 = i*M + j
    #         for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
    #             if not (0 <= x < N and 0 <= y < M):
    #                 continue
    #             v1 = x*M + y
    #             g.add_edge(v0, v1, 1)

    # print(g.max_flow(s, t))
    # for from_, to, _, flow in g.edges():
    #     if from_ in {s, t} or to in {s, t} or flow == 0:
    #         continue
    #     i0 = from_ // M
    #     j0 = from_ % M
    #     i1 = to // M
    #     j1 = to % M

    #     if i0 == i1+1:
    #         S[i1][j1] = 'v'
    #         S[i0][j0] = '^'
    #     elif j0 == j1+1:
    #         S[i1][j1] = '>'
    #         S[i0][j0] = '<'
    #     elif i0 == i1-1:
    #         S[i1][j1] = '^'
    #         S[i0][j0] = 'v'
    #     else:
    #         S[i1][j1] = '<'
    #         S[i0][j0] = '>'

    # for s in S:
    #     print(''.join(s))


def main():
    N, M = read_int_n()
    S = [read_str() for _ in range(N)]
    slv(N, M, S)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter
import queue

import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


class Dinic:
    def __init__(self, v):
        self.V = v
        self.G = [list() for _ in range(v)]
        self.level = [0 for _ in range(v)]
        self.iter = [0 for _ in range(v)]
        self.pos = []

    def add_edge(self, from_, to, cap):
        self.pos.append((from_, len(self.G[from_])))
        # to: 行き先, cap: 容量, rev: 反対側の辺
        # 0           1          2
        self.G[from_].append([to, cap, len(self.G[to])])
        self.G[to].append([from_, 0, len(self.G[from_])-1])


    def edges(self):
        es = []
        for f, t in self.pos:
            e = self.G[f][t]
            re = self.G[e[0]][e[2]]
            # from, to, cap, flow
            e = [f, e[0], e[1] + re[1], re[1]]
            es.append(e)
        return es

    # sからの最短距離をbfsで計算
    def bfs(self, s):
        self.level = [-1 for _ in range(self.V)]
        self.level[s] = 0
        que = queue.Queue()
        que.put(s)
        while not que.empty():
            v = que.get()
            for i in range(len(self.G[v])):
                e = self.G[v][i]
                if e[1] > 0 and self.level[e[0]] < 0:
                    self.level[e[0]] = self.level[v] + 1
                    que.put(e[0])

    # 増加バスをdfsで探す
    def dfs(self, v, t, f):
        if v == t:
            return f
        for i in range(self.iter[v], len(self.G[v])):
            self.iter[v] = i
            e = self.G[v][i]
            if e[1] > 0 and self.level[v] < self.level[e[0]]:
                d = self.dfs(e[0], t, min(f, e[1]))
                if d > 0:
                    e[1] -= d
                    self.G[e[0]][e[2]][1] += d
                    return d

        return 0

    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            # bfsで到達不可
            if self.level[t] < 0:
                return flow
            self.iter = [0 for _ in range(self.V)]
            f = self.dfs(s, t, INF)
            while f > 0:
                flow += f
                f = self.dfs(s, t, INF)


@mt
def slv(N, M, S):
    S = [list(s) for s in S]
    g = Dinic(N*M+2)
    s = N*M
    t = s + 1

    for i in range(N):
        for j in range(M):
            if S[i][j] == '#':
                continue
            v = i*M + j
            if (i + j )%2 == 0:
                g.add_edge(s, v, 1)
            else:
                g.add_edge(v, t, 1)

    for i in range(N):
        for j in range(M):
            if S[i][j] == '#':
                continue
            if (i+j) % 2 == 1:
                continue
            v0 = i*M + j
            for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
                if not (0 <= x < N and 0 <= y < M):
                    continue
                v1 = x*M + y
                g.add_edge(v0, v1, 1)

    print(g.max_flow(s, t))
    for f, t, _, flow in g.edges():
        if f in {s, t} or t in {s, t} or flow == 0:
            continue
        i0 = f // M
        j0 = f % M
        i1 = t // M
        j1 = t % M

        if i0 == i1+1:
            S[i1][j1] = 'v'
            S[i0][j0] = '^'
        elif j0 == j1+1:
            S[i1][j1] = '>'
            S[i0][j0] = '<'
        elif i0 == i1-1:
            S[i1][j1] = '^'
            S[i0][j0] = 'v'
        else:
            S[i1][j1] = '<'
            S[i0][j0] = '>'

    for s in S:
        print(''.join(s))


def main():
    N, M = read_int_n()
    S = [read_str() for _ in range(N)]
    slv(N, M, S)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#test
class maxFlow:
  def __init__(self, num):
    self.Len = num
    self.L = [[0] * num for i in range(num)]

  def setL(self, a, b, x):
    self.L[a][b] = x

  def getL(self, a, b):
    return self.L[a][b]

  def setLR(self, a, b, x):
    self.setL(a, b, x)
    self.setL(b, a, x)

  def setS(self, s, X, Y):
    for i in range(len(X)):
      self.setL(s, X[i], Y[i])

  def setSn(self, s, X, n):
    Y = [n for i in range(len(X))]
    self.setS(s, X, Y)

  def setT(self, t, X, Y):
    for i in range(len(X)):
      self.setL(X[i], t, Y[i])

  def setTn(self, t, X, n):
    Y = [n for i in range(len(X))]
    self.setT(t, X, Y)

  def getAns(self, t):
    return sum(self.L[t])

  def DFS(self, s, t):
    S = [[s, 1]]
    P = [0] * (self.Len + 1)
    D = [0] * self.Len
    while S != []:
      k = S.pop()
      P[k[1]] = k[0]
      if self.L[k[0]][self.Len - 1] > 0:
        P[k[1] + 1] = self.Len - 1
        P[0] = k[1] + 2
        return P
      for i in range(self.Len):
        if D[i] == 0 and self.L[k[0]][i] > 0:
          S.append([i, k[1] + 1])
          D[i] = 1
    return False

  def exe(self):
    while True:
      P = self.DFS(self.Len - 2, self.Len - 1)
      if P == False:
        break
      mi = self.L[P[1]][P[2]]
      for i in range(3, P[0]):
        if P[i - 1] == self.Len - 1:
          break
        t = self.L[P[i - 1]][P[i]]
        if t < mi:
          mi = t
      for i in range(2, P[0]):
        self.L[P[i - 1]][P[i]] -= mi
        self.L[P[i]][P[i - 1]] += mi

N, M = list(map(int, input().split()))
S = [list(input()) for _ in range(N)]

stop = "#"

flow = maxFlow(N * M + 2)
s = N * M
t = N * M + 1
for x in range(N):
  for y in range(M):
    if S[x][y] == stop: continue
    p = (x + y) % 2
    n = x * M + y
    if p:
      flow.setL(s, n, 1)
      for h, w in [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]]:
        if h < 0: continue
        if h >= N: continue
        if w < 0: continue
        if w >= M: continue
        if S[h][w] == stop: continue
        m = h * M + w
        flow.setL(n, m, 1)
    else:
      flow.setL(n, t, 1)

flow.exe()

print(flow.getAns(t))

Submission status: Wrong Answer

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import maximum_flow, maximum_bipartite_matching
import copy
N, M = [int(_) for _ in input().split()]
A = [list(input()) for _ in range(N)]
A2 = copy.deepcopy(A)
S = ''.join(''.join(a) for a in A)

X = []
Y = []
for i in range(N * M):
    if S[i] == '#':
        continue
    x, y = divmod(i, M)
    if (x - y) % 2 == 0:
        continue
    for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        nx, ny = x + dx, y + dy
        i2 = nx * M + ny
        if not (0 <= nx < N and 0 <= ny < M):
            continue
        if S[i2] == '#':
            continue
        X += [i]
        Y += [i2]
if not X:
    print(0)
    exit()
perm = maximum_bipartite_matching(csr_matrix(([1] * len(X), (X, Y))))
print((perm != -1).sum())
for i, j in enumerate(perm):
    if j == -1:
        continue
    if i > j:
        i, j = j, i
    x1, y1 = divmod(i, M)
    x2, y2 = divmod(j, M)
    if j == i + 1:
        A2[x1][y1] = '>'
        A2[x2][y2] = '<'
    else:
        A2[x1][y1] = 'v'
        A2[x2][y2] = '^'
ans = []
for ss in A2:
    ans += [''.join(ss)]
print('\n'.join(ans))

Submission status: Wrong Answer

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import maximum_flow, maximum_bipartite_matching
import copy
N, M = [int(_) for _ in input().split()]
A = [list(input()) for _ in range(N)]
A2 = copy.deepcopy(A)
S = ''.join(''.join(a) for a in A)

X = []
Y = []
for i in range(N * M):
    if S[i] == '#':
        continue
    x, y = divmod(i, M)
    if (x - y) % 2 == 0:
        continue
    for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        nx, ny = x + dx, y + dy
        i2 = nx * M + ny
        if not (0 <= nx < N and 0 <= ny < M):
            continue
        if S[i2] == '#':
            continue
        X += [i]
        Y += [i2]
if not X:
    print(0)
    exit()
perm = maximum_bipartite_matching(
    csr_matrix(([1] * len(X), (X, Y)), (N * M, N * M)))
print((perm != -1).sum())
for i, j in enumerate(perm):
    if j == -1:
        continue
    if i > j:
        i, j = j, i
    x1, y1 = divmod(i, M)
    x2, y2 = divmod(j, M)
    if j == i + 1:
        A2[x1][y1] = '>'
        A2[x2][y2] = '<'
    else:
        A2[x1][y1] = 'v'
        A2[x2][y2] = '^'
ans = []
for ss in A2:
    ans += [''.join(ss)]
print('\n'.join(ans))

Submission status: Wrong Answer

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import maximum_flow, maximum_bipartite_matching
import copy
N, M = [int(_) for _ in input().split()]
A = [['#'] * (M + 2)] + [list('#' + input() + '#')
                         for _ in range(N)] + [['#'] * (M + 2)]
A2 = copy.deepcopy(A)
S = ''.join(''.join(a) for a in A)

X = []
Y = []
for i in range((N + 2) * (M + 2)):
    if S[i] == '#':
        continue
    x, y = divmod(i, M + 2)
    if (x - y) % 2 == 0:
        continue
    if x in [0, N + 1]:
        continue
    if y in [0, M + 1]:
        continue
    for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        nx, ny = x + dx, y + dy
        i2 = nx * (M + 2) + ny
        if S[i2] == '#':
            continue
        X += [i]
        Y += [i2]
if not X:
    print(0)
    exit()
perm = maximum_bipartite_matching(csr_matrix(([1] * len(X), (X, Y))))
print((perm != -1).sum())
for i, j in enumerate(perm):
    if j == -1:
        continue
    if i > j:
        i, j = j, i
    x1, y1 = divmod(i, M + 2)
    x2, y2 = divmod(j, M + 2)
    if j == i + 1:
        A2[x1][y1] = '>'
        A2[x2][y2] = '<'
    else:
        A2[x1][y1] = 'v'
        A2[x2][y2] = '^'
ans = []
for ss in A2[1:-1]:
    ans += [''.join(ss[1:-1])]
print('\n'.join(ans))

Submission status: Wrong Answer

Solution code:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import maximum_flow, maximum_bipartite_matching
import copy
N, M = [int(_) for _ in input().split()]
A = [['#'] * (M + 2)] + [list('#' + input() + '#')
                         for _ in range(N)] + [['#'] * (M + 2)]
A2 = copy.deepcopy(A)
S = ''.join(''.join(a) for a in A)

X = []
Y = []
for i in range((N + 2) * (M + 2)):
    if S[i] == '#':
        continue
    x, y = divmod(i, M + 2)
    if (x - y) % 2:
        continue
    if x in [0, N + 1]:
        continue
    if y in [0, M + 1]:
        continue
    for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        nx, ny = x + dx, y + dy
        i2 = nx * (M + 2) + ny
        if S[i2] == '#':
            continue
        X += [i]
        Y += [i2]
if not X:
    print(0)
    exit()
perm = maximum_bipartite_matching(csr_matrix(([1] * len(X), (X, Y))))
print((perm != -1).sum())
for i, j in enumerate(perm):
    if j == -1:
        continue
    if i > j:
        i, j = j, i
    x1, y1 = divmod(i, M + 2)
    x2, y2 = divmod(j, M + 2)
    if j == i + 1:
        A2[x1][y1] = '>'
        A2[x2][y2] = '<'
    else:
        A2[x1][y1] = 'v'
        A2[x2][y2] = '^'
ans = []
for ss in A2[1:-1]:
    ans += [''.join(ss[1:-1])]
print('\n'.join(ans))

Submission status: Wrong Answer

Solution code:
import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10**9)
INF = 10**19
MOD = 10**9 + 7
EPS = 10**-10

def build_grid(H, W, intv, _type, space=False, padding=True):
    # 入力がスペース区切りかどうか
    if space:
        _input = lambda: input().split()
    else:
        _input = lambda: input()
    _list = lambda: list(map(_type, _input()))
    # 余白の有無
    if padding:
        offset = 1
    else:
        offset = 0
    grid = list2d(H+offset*2, W+offset*2, intv)
    for i in range(offset, H+offset):
        row = _list()
        for j in range(offset, W+offset):
            grid[i][j] = row[j-offset]
    return grid

class Dinic:
    """ 最大流(Dinic)：O(E*V^2) """

    INF = 10**18

    def __init__(self, n):
        self.n = n
        self.links = [[] for _ in range(n)]
        self.depth = None
        self.progress = None
        self.pos = []

    def copy(self):
        res = Dinic(self.n)
        res.links = [[a[:] for a in b] for b in self.links]
        res.pos = [a[:] for a in self.pos]
        return res

    def add_edge(self, _from, to, cap):
        self.pos.append((_from, len(self.links[_from])))
        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):
        from collections import deque

        depth = [-1] * self.n
        depth[s] = 0
        q = deque([s])
        while q:
            v = q.popleft()
            for cap, to, _ 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 flow(self, s, t):
        INF = Dinic.INF
        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, INF)
            while current_flow > 0:
                flow += current_flow
                current_flow = self.dfs(s, t, INF)

    def get_edge(self, i):
        e = self.links[self.pos[i][0]][self.pos[i][1]]
        re = self.links[e[1]][e[2]]
        # from, to, cap, flow
        return (self.pos[i][0], e[1], e[0]+re[0], re[0])

    def get_edges(self):
        M = len(self.pos)
        res = []
        for i in range(M):
            res.append(self.get_edge(i))
        return res

N, M = MAP()
grid = build_grid(N, M, '#', str)
N += 2; M += 2

dinic = Dinic(N*M+2)
s = N*M
t = N*M + 1

directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
for i in range(1, N-1):
    for j in range(1, M-1):
        if grid[i][j] == '#':
            continue
        u = M*i + j
        if (i+j) % 2 == 1:
            dinic.add_edge(s, u, 1)
        else:
            dinic.add_edge(u, t, 1)
        for di, dj in directions:
            ni, nj = i+di, j+dj
            v = M*ni + nj
            if grid[ni][nj] == '.':
                dinic.add_edge(u, v, 1)

res = dinic.flow(s, t)
edges = dinic.get_edges()
for u, v, cap, f in edges:
    if u not in [s, t] and v not in [s, t] and f:
        ci, cj = divmod(u, M)
        ni, nj = divmod(v, M)
        if ci+1 == ni:
            grid[ci][cj] = 'v'
            grid[ni][nj] = '^'
        elif ci == ni+1:
            grid[ci][cj] = '^'
            grid[ni][nj] = 'v'
        elif cj+1 == nj:
            grid[ci][cj] = '>'
            grid[ni][nj] = '<'
        elif cj == nj+1:
            grid[ci][cj] = '<'
            grid[ni][nj] = '>'

print(res)
for i in range(1, N-1):
    print(''.join(grid[i][1:M-1]))