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: Accepted

Solution code:
import os
import sys

import numpy as np


def solve(n, m, sss):
    BIT_SHIFT = 9
    BIT_MASK = (1 << BIT_SHIFT) - 1

    def combine_rc(r, c):
        return (r << BIT_SHIFT) | c

    def separate_rc(rc):
        return rc >> BIT_SHIFT, rc & BIT_MASK

    DINIC_LINKS = []
    DINIC_PAIRS = []

    def dinic_init(n):
        lst = [[0, 0, 0]]
        lst.clear()
        DINIC_LINKS.append([lst.copy() for _ in range(n)])
        DINIC_PAIRS.append(np.full(n, -1, dtype=np.int64))

    def dinic_add_link(ins, frm, to, cap):
        links = DINIC_LINKS[ins]
        links[frm].append([cap, to, len(links[to])])
        links[to].append([0, frm, len(links[frm]) - 1])

    def dinic_bfs(ins, n, s):
        links = DINIC_LINKS[ins]
        depth = np.full(n, -1, dtype=np.int64)
        depth[s] = 0
        deq = np.zeros(n + 5, dtype=np.int64)
        dl, dr = 0, 1
        deq[0] = s
        while dl < dr:
            v = deq[dl]
            dl += 1
            for link in links[v]:
                if link[0] > 0 and depth[link[1]] == -1:
                    depth[link[1]] = depth[v] + 1
                    deq[dr] = link[1]
                    dr += 1
        return depth

    def dinic_dfs(ins, depth, progress, s, t):
        links = DINIC_LINKS[ins]
        pairs = DINIC_PAIRS[ins]
        stack = [(0, s, 10 ** 18)]
        flow = 0
        while stack:
            phase, v, f = stack.pop()
            if v == t:
                flow = f
                continue
            if phase == 0 or flow == 0:
                i = progress[v]
                if i == len(links[v]):
                    continue
                progress[v] += 1
                stack.append((1, v, f))
                cap, to, rev = links[v][i]
                if cap == 0 or depth[v] >= depth[to]:
                    continue
                stack.append((0, to, min(f, cap)))
            else:
                i = progress[v] - 1
                link = links[v][i]
                link[0] -= flow
                links[link[1]][link[2]][0] += flow
                pairs[v] = link[1]
        return flow

    def dinic_maximum_flow(ins, n, s, t):
        flow = 0
        while True:
            depth = dinic_bfs(ins, n, s)
            if depth[t] == -1:
                return flow
            progress = np.zeros(n, dtype=np.int64)
            path_flow = dinic_dfs(ins, depth, progress, s, t)
            while path_flow != 0:
                flow += path_flow
                path_flow = dinic_dfs(ins, depth, progress, s, t)

    lefts = []
    rights = []
    rights_rev = {}

    for r in range(1, n + 1):
        for c in range(1, m + 1):
            if sss[r, c]:
                continue
            rc = combine_rc(r, c)
            if (r ^ c) & 1:
                lefts.append(rc)
            else:
                rights_rev[rc] = len(rights)
                rights.append(rc)
    l_size = len(lefts)
    r_size = len(rights)
    s = l_size + r_size
    t = s + 1
    total_size = t + 1

    dinic_init(total_size)

    MOVE = (-(1 << BIT_SHIFT), -1, 1, 1 << BIT_SHIFT)

    for i in range(l_size):
        rc = lefts[i]
        for drc in MOVE:
            nrc = rc + drc
            if nrc in rights_rev:
                dinic_add_link(0, i, rights_rev[nrc] + l_size, 1)
        dinic_add_link(0, s, i, 1)
    for j in range(r_size):
        dinic_add_link(0, j + l_size, t, 1)

    flow = dinic_maximum_flow(0, total_size, s, t)
    pairs = DINIC_PAIRS[0]

    for i in range(l_size):
        j = pairs[i]
        if j == -1:
            continue
        ir, ic = separate_rc(lefts[i])
        jr, jc = separate_rc(rights[j - l_size])
        if ir == jr:
            if ic > jc:
                ic, jc = jc, ic
            sss[ir, ic] = 4
            sss[jr, jc] = 5
        else:
            if ir > jr:
                ir, jr = jr, ir
            sss[ir, ic] = 2
            sss[jr, jc] = 3

    return flow


SIGNATURE = '(i8,i8,i1[:,:],)'
if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC

    cc = CC('my_module')
    cc.export('solve', SIGNATURE)(solve)
    cc.compile()
    exit()

if os.name == 'posix':
    # noinspection PyUnresolvedReferences
    from my_module import solve
else:
    from numba import njit

    solve = njit(SIGNATURE, cache=True)(solve)
    print('compiled', file=sys.stderr)

n, m = map(int, input().split())
sss = np.ones((n + 2, m + 2), dtype=np.int8)
for i in range(n):
    sss[i + 1, 1:m + 1] = list(map('.#'.index, input()))

ans = solve(n, m, sss)
print(ans)
CHARS = '.#v^><'.__getitem__
for i in range(1, n + 1):
    print(''.join(map(CHARS, sss[i, 1:m + 1])))

Submission status: Accepted

Solution code:
import networkx as nx

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

  if N == M == 1:
    print(0)
    print(S[0][0])
    exit()

  index = lambda i,j: i*M+j

  G=nx.Graph()
  dx,dy=(1,0),(0,1)
  E = []
  n1,n2 = [],[]
  for i in range(N):
    for j in range(M):
      if S[i][j]=='#':continue
      if (i+j)%2: n1.append(index(i,j))
      else: n2.append(index(i,j))
      for k in range(2):
        v1,v2 = index(i,j),index(i+dx[k],j+dy[k])
        if not (0<=i+dx[k]<N and 0<=j+dy[k]<M): continue
        if S[i+dx[k]][j+dy[k]] == '#': continue
        if (i+j) % 2: E.append((v2,v1))
        else: E.append((v1,v2))
     
  G.add_nodes_from(n1, bipartite=0)
  G.add_nodes_from(n2, bipartite=1)
  G.add_edges_from(E)
  match = nx.bipartite.maximum_matching(G, top_nodes=n1)
  match = {v:match[v] for v in match.keys() if v < match[v]}
 
  for v in match.keys():
    i1,j1 = divmod(v,M)
    i2,j2 = divmod(match[v],M)
    if i1 > i2 or j1 > j2:
      (i1,j1),(i2,j2) = (i2,j2),(i1,j1)
    if i1 < i2:
      S[i1][j1] = 'v'
      S[i2][j2] = '^'
    else:
      S[i1][j1] = '>'
      S[i2][j2] = '<'

  print(len(match))
  for i in range(N):
    print(''.join(S[i]))
    
if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
import networkx as nx

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

  if N == M == 1:
    print(0)
    print(S[0][0])
    exit()

  index = lambda i,j: i*M+j

  G=nx.Graph()
  dx,dy=(1,0),(0,1)
  E = []
  n1,n2 = [],[]
  for i in range(N):
    for j in range(M):
      if S[i][j]=='#':continue
      if (i+j)%2:
        n1.append(index(i,j))
      else:
        n2.append(index(i,j))
      for k in range(2):
        v1,v2 = index(i,j),index(i+dx[k],j+dy[k])
        if not (0<=i+dx[k]<N and 0<=j+dy[k]<M):
          continue
        if S[i+dx[k]][j+dy[k]] == '#': continue
        if (i+j) % 2:
          E.append((v2,v1))
        else:
          E.append((v1,v2))
     
  G.add_nodes_from(n1, bipartite=0)
  G.add_nodes_from(n2, bipartite=1)
  G.add_edges_from(E)
  u = [n for n in G.nodes if G.nodes[n]['bipartite'] == 0]
  match = nx.bipartite.maximum_matching(G, top_nodes=u)
  match = {v:match[v] for v in match.keys() if v < match[v]}
 
  for v in match.keys():
    i1,j1 = divmod(v,M)
    i2,j2 = divmod(match[v],M)
    if i1 > i2 or j1 > j2:
      (i1,j1),(i2,j2) = (i2,j2),(i1,j1)
    if i1 < i2:
      S[i1][j1] = 'v'
      S[i2][j2] = '^'
    else:
      S[i1][j1] = '>'
      S[i2][j2] = '<'

  print(len(match))
  for i in range(N):
    print(''.join(S[i]))
    
if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
# Date [ 2020-09-08 14:10:26 ]
# Problem [ d.py ]
# Author Koki_tkg

import sys
# import math
# import bisect
# import numpy as np
# from decimal import Decimal
# from numba import njit, i8, u1, b1 #JIT compiler
# from itertools import combinations, product
from collections import Counter, deque, defaultdict

# sys.setrecursionlimit(10 ** 6)
MOD = 10 ** 9 + 7
INF = 10 ** 9
PI = 3.14159265358979323846

def read_str():      return sys.stdin.readline().strip()
def read_int():      return int(sys.stdin.readline().strip())
def read_ints():     return map(int, sys.stdin.readline().strip().split())
def read_ints2(x):   return map(lambda num: int(num) - x, sys.stdin.readline().strip().split())
def read_str_list(): return list(sys.stdin.readline().strip().split())
def read_int_list(): return list(map(int, sys.stdin.readline().strip().split()))
def GCD(a: int, b: int) -> int: return b if a%b==0 else GCD(b, a%b)
def LCM(a: int, b: int) -> int: return (a * b) // GCD(a, b)

# Dinic's algorithm
class Dinic:
    def __init__(self, n):
        self.N = n
        self.level = None
        self.it = None
        self.G = [[] for i in range(self.N)]

    def add_edge(self, _from, _to, cap):
        self.G[_from].append([_to, cap, len(self.G[_to])])
        self.G[_to].append([_from, 0, len(self.G[_from]) - 1])

    def add_multi_edge(self, v1, v2, cap1, cap2):
        edge1 = [v2, cap1, None]
        edge1[2] = edge2 = [v1, cap2, edge1]
        self.G[v1].append(edge1)
        self.G[v2].append(edge2)

    def bfs(self, s):
        level = [-1] * self.N
        level[s] = 0
        que = deque([s])
        while que:
            v = que.popleft()
            for to, cap, rev in self.G[v]:
                if cap > 0 and level[to] < 0:
                    level[to] = level[v] + 1
                    que.append(to)
        self.level = level

    def dfs(self, v, t, flow):
        if v == t: return flow
        for i in range(self.it[v], len(self.G[v])):
            self.it[v] = i
            to, cap, rev = e =self.G[v][i]
            if cap > 0 and self.level[v] < self.level[to]:
                d = self.dfs(to, t, min(flow, cap))
                if d > 0:
                    e[1] -= d
                    self.G[to][rev][1] += d
                    return d
        return 0

    def max_flow(self, s, t):
        flow = 0
        INF = 10**18
        while True:
            self.bfs(s)
            if self.level[t] < 0: return flow
            self.it = [0] * self.N
            f = self.dfs(s, t, INF)
            while f > 0:
                flow += f
                f = self.dfs(s, t, INF)

def Main():
    n, m = read_ints()
    grid = [list(read_str()) for _ in range(n)]
    mf = Dinic(n*m + 2)
    start = n * m
    end = start + 1
    dir = [(1, 0), (0, 1)]
    
    for y in range(n):
        for x in range(m):
            if (y + x) % 2 == 0:
                mf.add_edge(start, m*y + x, 1)
            else:
                mf.add_edge(m*y + x, end, 1)
            
            if grid[y][x] == '.':
                for dy, dx in dir:
                    ny = y + dy; nx = x + dx
                    if ny < n and nx < m and grid[ny][nx] == '.':
                        f, t = y*m + x, ny*m + nx
                        if (y + x) % 2: f, t = t, f
                        mf.add_edge(f, t, 1)

    ans = mf.max_flow(start, end)    

    for y in range(n):
        for x in range(m):
            for to, cap, rev in mf.G[y*m+x]:
                ny, nx = divmod(to, m)
                if (y + x) % 2 == 0 and cap == 0 and to != start and to != end and (y*m+x) != start and (y*m+x) != end:
                    if y + 1 == ny: grid[y][x] = 'v'; grid[ny][nx] = '^'
                    elif y == ny + 1: grid[y][x] = '^'; grid[ny][nx] = 'v'
                    elif x + 1 == nx: grid[y][x] = '>'; grid[ny][nx] = '<'
                    elif x == nx + 1: grid[y][x] = '<'; grid[ny][nx] = '>'
                        
    print(ans)
    print(*[''.join(ret) for ret in grid], sep='\n')

if __name__ == '__main__':
    Main()

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
# import time,random,resource

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)
def IF(c, t, f): return t if c else f


class Flow():
    def __init__(self, e, N):
        self.E = e
        self.N = N
        self.nl = list(range(N))

    def max_flow(self, s, t):
        r = 0
        e = self.E
        v = None

        def f(c):
            v[c] = 1
            if c == t:
                return 1
            for i in e[c]:
                if v[i] is None and f(i):
                    e[c].remove(i)
                    e[i].add(c)
                    return 1
            return

        while True:
            v = [None] * self.N
            if f(s) is None:
                break
            r += 1

        return r


def main():
    n,m = LI()
    sa = [S() for _ in range(n)]

    e = collections.defaultdict(set)
    s = n*m
    t = n*m + 1
    for i in range(n):
        for j in range(m):
            if sa[i][j] == '#':
                continue

            ij = i*m+j
            if (i+j) % 2 == 1:
                e[ij].add(t)
                continue

            e[s].add(ij)
            for di,dj in dd:
                ni = i + di
                nj = j + dj
                if ni < 0 or ni >= n or nj < 0 or nj >= m or sa[ni][nj] == '#':
                    continue
                e[ij].add(ni*m+nj)

    fl = Flow(e, n*m+2)
    r = fl.max_flow(s,t)
    ra = [[c for c in s] for s in sa]
    for i in range(n):
        for j in range(m):
            ij = i*m+j
            if sa[i][j] == '#' or (i+j) % 2 == 1 or ij in e[s]:
                continue

            ni = nj = 0
            for di, dj in dd:
                ni = i + di
                nj = j + dj
                if ni < 0 or ni >= n or nj < 0 or nj >= m or sa[ni][nj] == '#':
                    continue

                if ni*m+nj not in e[ij]:
                    break

            if ni < i:
                ra[ni][j] = 'v'
                ra[i][j] = '^'
            elif ni > i:
                ra[i][j] = 'v'
                ra[ni][j] = '^'
            elif nj < j:
                ra[i][nj] = '>'
                ra[i][j] = '<'
            else:
                ra[i][j] = '>'
                ra[i][nj] = '<'

    return f"{r}\n" + JAA(ra, "\n", "")


print(main())

Submission status: Accepted

Solution code:
import networkx as nx

BIT_SHIFT = 9
BIT_MASK = (1 << BIT_SHIFT) - 1


def combine_rc(r, c):
    return (r << BIT_SHIFT) | c


def separate_rc(rc):
    return rc >> BIT_SHIFT, rc & BIT_MASK


def solve(n, m, sss):
    m2 = m + 2
    lefts = set()
    rights = set()

    for r in range(1, n + 1):
        for c in range(1, m + 1):
            if sss[r][c] == '#':
                continue
            rc = combine_rc(r, c)
            if (r ^ c) & 1:
                lefts.add(rc)
            else:
                rights.add(rc)

    edges = []
    MOVE = (-(1 << BIT_SHIFT), -1, 1, 1 << BIT_SHIFT)
    for rc in lefts:
        for d in MOVE:
            nrc = rc + d
            if nrc in rights:
                edges.append((rc, nrc))
    BG = nx.Graph()
    BG.add_nodes_from(lefts, bipartite=0)
    BG.add_nodes_from(rights, bipartite=1)
    BG.add_edges_from(edges)

    ans = 0
    for sub in nx.connected_components(BG):
        matched = nx.bipartite.maximum_matching(BG.subgraph(sub))

        for rc1, rc2 in matched.items():
            r1, c1 = separate_rc(rc1)
            if (r1 ^ c1) & 1:
                continue
            r2, c2 = separate_rc(rc2)
            if r1 == r2:
                if c1 > c2:
                    c1, c2 = c2, c1
                sss[r1][c1] = '>'
                sss[r2][c2] = '<'
            else:
                if r1 > r2:
                    r1, r2 = r2, r1
                sss[r1][c1] = 'v'
                sss[r2][c2] = '^'
            ans += 1

    return ans


n, m = map(int, input().split())
n2, m2 = n + 2, m + 2
sss = [['#'] * m2 for _ in range(n2)]
for i in range(1, n + 1):
    sss[i][1:m + 1] = list(input())

ans = solve(n, m, sss)
print(ans)
for i in range(1, n + 1):
    print(''.join(sss[i][1:m + 1]))

Submission status: Accepted

Solution code:
import os
import sys

import numpy as np


def solve(n, m, sss):
    BIT_SHIFT = 9
    BIT_MASK = (1 << BIT_SHIFT) - 1

    def combine_rc(r, c):
        return (r << BIT_SHIFT) | c

    def separate_rc(rc):
        return rc >> BIT_SHIFT, rc & BIT_MASK

    def increase_update(matched, ancestors_l, ancestors_r, s, b):
        a = ancestors_r[b]
        while s != a:
            matched[b] = a
            b = ancestors_l[a]
            a = ancestors_r[b]
        matched[b] = a

    def increase(s, l_size, r_size, edges, matched):
        ancestors_l = np.full(l_size, -1, dtype=np.int64)
        ancestors_r = np.full(r_size, -1, dtype=np.int64)
        deq = np.zeros(l_size + 5, dtype=np.int64)
        dl, dr = 0, 1
        deq[0] = s
        stacked = np.zeros(l_size, dtype=np.int8)
        stacked[s] = 1
        while dl < dr:
            a = deq[dl]
            dl += 1
            k = 0
            while edges[a, k] != -1:
                b = edges[a, k]
                c = matched[b]
                if c == -1:
                    ancestors_r[b] = a
                    increase_update(matched, ancestors_l, ancestors_r, s, b)
                    return b
                if stacked[c] == 0:
                    ancestors_l[c] = b
                    ancestors_r[b] = a
                    deq[dr] = c
                    dr += 1
                    stacked[c] = 1
                k += 1
        return -1

    lefts = []
    rights = []
    rights_rev = {}

    for r in range(1, n + 1):
        for c in range(1, m + 1):
            if sss[r, c]:
                continue
            rc = combine_rc(r, c)
            if (r ^ c) & 1:
                lefts.append(rc)
            else:
                rights_rev[rc] = len(rights)
                rights.append(rc)
    l_size = len(lefts)
    r_size = len(rights)

    MOVE = (-(1 << BIT_SHIFT), -1, 1, 1 << BIT_SHIFT)

    edges = np.full((l_size, 5), -1, dtype=np.int64)
    for i in range(l_size):
        rc = lefts[i]
        k = 0
        for drc in MOVE:
            nrc = rc + drc
            if nrc in rights_rev:
                edges[i, k] = rights_rev[nrc]
                k += 1

    matched = np.full(r_size, -1, dtype=np.int64)
    for i in range(l_size):
        increase(i, l_size, r_size, edges, matched)

    # v:2 ^:3 >:4 <:5
    ans = 0
    for j in range(r_size):
        i = matched[j]
        if i == -1:
            continue
        ir, ic = separate_rc(lefts[i])
        jr, jc = separate_rc(rights[j])
        if ir == jr:
            if ic > jc:
                ic, jc = jc, ic
            sss[ir, ic] = 4
            sss[jr, jc] = 5
        else:
            if ir > jr:
                ir, jr = jr, ir
            sss[ir, ic] = 2
            sss[jr, jc] = 3
        ans += 1

    return ans


SIGNATURE = '(i8,i8,i1[:,:],)'
if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC

    cc = CC('my_module')
    cc.export('solve', SIGNATURE)(solve)
    cc.compile()
    exit()

if os.name == 'posix':
    # noinspection PyUnresolvedReferences
    from my_module import solve
else:
    from numba import njit

    solve = njit(SIGNATURE, cache=True)(solve)
    print('compiled', file=sys.stderr)

n, m = map(int, input().split())
sss = np.ones((n + 2, m + 2), dtype=np.int8)
for i in range(n):
    sss[i + 1, 1:m + 1] = list(map('.#'.index, input()))

ans = solve(n, m, sss)
print(ans)
CHARS = '.#v^><'.__getitem__
for i in range(1, n + 1):
    print(''.join(map(CHARS, sss[i, 1:m + 1])))

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
S=[list(input()) for i in range(N)]
V=N*M
G=[[] for i in range(V)]
match=[0]*V
used=[0]*V
def ae(u,v):
  G[u].append(v)
  G[v].append(u)

def dfs(v):
  used[v]=1
  u,w=0,0
  for i in range(len(G[v])):
    u=G[v][i]
    w=match[u]
    if (w<0)or((not(used[w]))and(dfs(w))):
      match[v]=u
      match[u]=v
      return 1
  return 0

def matching():
  r=0
  for i in range(V):
    match[i]=-1
  for v in range(V):
    if match[v]<0:
      for i in range(V):
        used[i]=0
      if dfs(v):
        r+=1
  return r

w4y=[1,0,-1,0]
w4x=[0,1,0,-1]
for i in range(N):
  for j in range(M):
    if ((i+j+1)&1)and(S[i][j]=='.'):
      for k in range(4):
        k=[i+w4y[k],j+w4x[k]]
        if min(k)<0 or k[0]>=N or k[1]>=M:
          continue
        if S[k[0]][k[1]]=='.':
          ae(i*M+j,k[0]*M+k[1])
print(matching())
for i in range(N):
  for j in range(M):
    if match[i*M+j]<0:
      continue
    if match[i*M+j]==i*M+j+M:
      S[i][j]='v'
    elif match[i*M+j]==i*M+j-M:
      S[i][j]='^'
    elif match[i*M+j]==i*M+j+1:
      S[i][j]='>'
    elif match[i*M+j]==i*M+j-1:
      S[i][j]='<'
  print(''.join(S[i]))

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
import collections
class Dinic:
    def __init__(self, vnum):
        self.edge = [[] for i in range(vnum)]
        self.n = vnum
        # infはint型の方が良いかもね
        self.inf = float('inf')
    def addedge(self, st, en, c):
        self.edge[st].append([en, c, len(self.edge[en])])
        self.edge[en].append([st, 0, len(self.edge[st])-1])
    def bfs(self, vst):
        dist = [-1]*self.n
        dist[vst] = 0
        Q = collections.deque([vst])
        while Q:
            nv = Q.popleft()
            for vt, c, r in self.edge[nv]:
                if dist[vt] == -1 and c > 0:
                    dist[vt] = dist[nv] + 1
                    Q.append(vt)
        self.dist = dist
    def dfs(self, nv, en, nf):
        nextv = self.nextv
        if nv == en:
            return nf
        dist = self.dist
        ist = nextv[nv]
        for i, (vt, c, r) in enumerate(self.edge[nv][ist:], ist):
            if dist[nv] < dist[vt] and c > 0:
                df = self.dfs(vt, en, min(nf, c))
                if df > 0:
                    self.edge[nv][i][1] -= df
                    self.edge[vt][r][1] += df
                    return df
            nextv[nv] += 1
        return 0
    def getmf(self, st, en):
        mf = 0
        while True:
            self.bfs(st)
            if self.dist[en] == -1:
                break
            self.nextv = [0]*self.n
            while True:
                fl = self.dfs(st, en, self.inf)
                if fl > 0:
                    mf += fl
                else:
                    break
        return mf


N, M = map(int, readline().split())

G = [[1 if s == '#' else 0 for s in readline().strip()] for _ in range(N)]

T = Dinic(2*N*M+2)
st = 2*N*M
en = st+1
geta = N*M
DIREC = ((1, 0), (-1, 0), (0, 1), (0, -1))


for i in range(N):
    for j in range(M):
        if not G[i][j]:
            if (i+j)%2:
                T.addedge(st, i*M+j, 1)
                for di, dj in DIREC:
                    ni, nj = i+di, j+dj
                    if 0 <= ni < N and 0 <= nj < M and not G[ni][nj]:
                        T.addedge(i*M+j, geta + ni*M+nj, 1)
            else:
                T.addedge(geta + i*M+j, en, 1)

print(T.getmf(st, en))

Ans = [g[:] for g in G]

for i in range(N):
    for j in range(M):
        if not (i+j)%2 and not G[i][j]:
            for vf, c, _ in T.edge[geta + M*i+j]:
                if c == 1 and vf != en:
                    ni, nj = divmod(vf, M)
                    if i == ni:
                        if j < nj:
                            Ans[i][j] = 2
                            Ans[ni][nj] = 3
                        else:
                            Ans[i][j] = 3
                            Ans[ni][nj] = 2
                    else:
                        if i < ni:
                            Ans[i][j] = 4
                            Ans[ni][nj] = 5
                        else:
                            Ans[i][j] = 5
                            Ans[ni][nj] = 4

D = ['.', '#', '>', '<', 'v', '^']

print('\n'.join(''.join(D[ai] for ai in a) for a in Ans))

Submission status: Accepted

Solution code:
from collections import deque


class Dinic:
    def __init__(self, n: int):
        self.n = n
        self.INF = 10 ** 9 + 7
        self.graph = [[] for _ in range(n)]

    def add_edge(self, _from: int, to: int, capacity: int):
        """辺の追加
        1. _fromからtoへ向かう容量capacityの辺をグラフに追加する。
        2. toから_fromへ向かう容量0の辺をグラフに追加する。
        """
        forward = [to, capacity, None]
        forward[2] = backward = [_from, 0, forward]
        self.graph[_from].append(forward)
        self.graph[to].append(backward)

    def bfs(self, s: int, t: int):
        """capacityが正の辺のみを通ってsからtに移動可能かどうかBFSで探索する。
        level: sからの最短路の長さ
        """
        self.level = [-1] * self.n
        q = deque([s])
        self.level[s] = 0
        while q:
            _from = q.popleft()
            for to, capacity, _ in self.graph[_from]:
                if capacity > 0 and self.level[to] < 0:
                    self.level[to] = self.level[_from] + 1
                    q.append(to)

    def dfs(self, _from: int, t: int, f: int) -> int:
        """流量が増加するパスをDFSで探索する。
        BFSによって作られた最短路に従ってfを更新する。
        """
        if _from == t:
            return f
        for edge in self.itr[_from]:
            to, capacity, reverse_edge = edge
            if capacity > 0 and self.level[_from] < self.level[to]:
                d = self.dfs(to, t, min(f, capacity))
                if d > 0:
                    edge[1] -= d
                    reverse_edge[1] += d
                    return d
        return 0

    def max_flow(self, s: int, t: int) -> int:
        """s-tパス上の最大流を求める。計算量: O(|E||V|^2)"""
        flow = 0
        while True:
            self.bfs(s, t)
            if self.level[t] < 0:
                break
            self.itr = list(map(iter, self.graph))
            f = self.dfs(s, t, self.INF)
            while f > 0:
                flow += f
                f = self.dfs(s, t, self.INF)
        return flow


n, m = map(int, input().split())
s = [list(input()) for i in range(n)]


dc = Dinic(n * m + 2)

# 始点、終点とグリッドに辺を貼る 
start = n * m
goal = n * m + 1
for i in range(n):
    for j in range(m):
        if (i + j) % 2 == 0:
            dc.add_edge(start, m * i + j, 1)
        else:
            dc.add_edge(m * i + j, goal, 1)
# グリッド間に辺を貼る 
for i in range(n):
    for j in range(m):
        if j + 1 < m and s[i][j] == "." and s[i][j + 1] == ".":
            u, v = m * i + j, m * i + j + 1
            if (i + j) % 2 == 1:
                u, v = v, u
            dc.add_edge(u, v, 1)
        if i + 1 < n and s[i][j] == "." and s[i + 1][j] == ".":
            u, v = m * i + j, m * (i + 1) + j
            if (i + j) % 2 == 1:
                u, v = v, u
            dc.add_edge(u, v, 1)

ans = dc.max_flow(start, goal)

for u in range(n * m + 2):
    for v, cap, _ in dc.graph[u]:
        ui, uj = divmod(u, m)
        vi, vj = divmod(v, m)
        if (ui + uj) % 2 == 0 and cap == 0 and u != start and u != goal and v != start and v!= goal:
            if ui + 1 == vi:
                s[ui][uj] = "v"
                s[vi][vj] = "^"
            elif ui == vi + 1:
                s[ui][uj] = "^"
                s[vi][vj] = "v"
            elif uj + 1 == vj:
                s[ui][uj] = ">"
                s[vi][vj] = "<"
            elif uj == vj + 1:
                s[ui][uj] = "<"
                s[vi][vj] = ">"

print(ans)
for res in s:
    print("".join(res))