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: Time Limit Exceeded

Solution code:
class mf_graph:
    def __init__(self, n=0):
        self._n = n
        self.g = [[] for _ in range(n)]
        self.pos = []
    
    def add_edge(self, frm, to, cap):
        m = len(self.pos)
        e1 = mf_graph._edge(to, cap)
        e2 = mf_graph._edge(frm, 0)
        e1.rev = e2
        e2.rev = e1
        self.pos.append(e1)
        self.g[frm].append(e1)
        self.g[to].append(e2)
        return m
    
    class edge:
        def __init__(self, frm, to, cap, flow):
            self.frm = frm
            self.to = to
            self.cap = cap
            self.flow = flow
        
        def __iter__(self):
            yield self.frm
            yield self.to
            yield self.cap
            yield self.flow
    
    def get_edge(self, i):
        e1 = self.pos[i]
        e2 = e1.rev
        return mf_graph.edge(e2.to, e1.to, e1.cap + e2.cap, e2.cap)
    
    def edges(self):
        return [self.get_edge(i) for i in range(len(self.pos))]
    
    def change_edge(self, i, new_cap, new_flow):
        e = self.pos[i]
        e.cap = new_cap - new_flow
        e.rev.cap = new_flow
    
    def flow(self, s, t, flow_limit=0XFFFFFFFFFFFFFFF):
        g = self.g
        flow = 0
        while flow < flow_limit:
            level = [-1] * self._n
            level[s] = 0
            que = [None] * self._n
            ql = 0
            qr = 1
            que[0] = s
            unreached = True
            while unreached and ql < qr:
                v = que[ql]
                ql += 1
                for e in g[v]:
                    to = e.to
                    if e.cap and level[to] < 0:
                        level[to] = level[v] + 1
                        if to == t:
                            unreached = False
                            break
                        que[qr] = to
                        qr += 1
            if unreached:
                return flow
            ptr = [len(es) for es in g]
            stack = []
            v = t
            up = flow_limit - flow
            res = 0
            while True:
                if v == s or not ptr[v]:
                    if v == s:
                        res = up
                    while stack:
                        tmp = res
                        e, up, res = stack.pop()
                        e.cap -= tmp
                        e.rev.cap += tmp
                        res += tmp
                        if res < up:
                            v = e.to
                            break
                    else:
                        flow += res
                        break
                else:
                    i = ptr[v]
                    while i:
                        i -= 1
                        e = g[v][i]
                        if level[e.to] == level[v] - 1:
                            ptr[v] = i
                            stack.append((e.rev, up, res))
                            v = e.to
                            up = min(up, e.rev.cap)
                            res = 0
                            break
                    else:
                        ptr[v] = i
        return flow
    
    def min_cut(self, s):
        visited = [False] * self._n
        que = [None] * self._n
        ql = 0
        qr = 1
        que[0] = s
        visited[s] = True
        while ql < qr:
            p = que[ql]
            ql += 1
            for e in self.g[p]:
                if e.cap and not visited[e.to]:
                    visited[e.to] = True
                    que[qr] = e.to
                    qr += 1
        return visited
    
    class _edge:
        def __init__(self, to, cap):
            self.to = to
            self.cap = cap

n, m = map(int, input().split())
s = [input() for _ in range(n)]
g = mf_graph(n * m + 2)
for i in range(n):
    for j in range(i % 2, m, 2):
        if s[i][j] == '#':
            continue
        for di, dj in (1, 0), (0, 1), (-1, 0), (0, -1):
            x, y = i + di, j + dj
            if 0 <= x < n and 0 <= y < m and s[x][y] == '.':
                g.add_edge(i * m + j, x * m + y, 1)
for i in range(n):
    for j in range(m):
        if s[i][j] == '#':
            continue
        if (i + j) % 2 == 0:
            g.add_edge(n * m, i * m + j, 1)
        else:
            g.add_edge(i * m + j, n * m + 1, 1)
print(g.flow(n * m, n * m + 1))
ans = [list(si) for si in s]
for frm, to, cap, flow in g.edges():
    if flow and frm < n * m and to < n * m:
        i, j = frm // m, frm % m
        x, y = to // m, to % m
        if j == y:
            if i > x:
                i, j, x, y = x, y, i, j
            ans[i][j], ans[x][y] = 'v^'
        else:
            if j > y:
                i, j, x, y = x, y, i, j
            ans[i][j], ans[x][y] = '><'

for a in ans:
    print(''.join(a))

Submission status: Time Limit Exceeded

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.DiGraph()
  G.add_node('source')
  G.add_node('sink')
  dx,dy=(1,0),(0,1)
  E = []
  for i in range(N):
    for j in range(M):
      if S[i][j]=='#':continue
      if (i+j) %2:
        E.append((index(i,j),'sink'))
      else:
        E.append(('source',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_edges_from(E,capacity=1)
  flow_value, flow_dict = nx.maximum_flow(G, "source", "sink")

  for v1 in flow_dict.keys():
    if v1 in ('sink','source'):continue
    for v2 in flow_dict[v1].keys():
      if v2 in ('sink','source'):continue
      if flow_dict[v1][v2]:
        i1,j1 = divmod(v1,M)
        i2,j2 = divmod(v2,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(flow_value)
  for i in range(N):
    print(''.join(S[i]))
    
if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

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.DiGraph()
  G.add_node('source')
  G.add_node('sink')
  dx,dy=(1,0),(0,1)
  for i in range(N):
    for j in range(M):
      if S[i][j]=='#':continue
      if (i+j) %2:
        G.add_edge(index(i,j),'sink',capacity=1)
      else:
        G.add_edge('source',index(i,j),capacity=1)
      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:
          G.add_edge(v2,v1,capacity=1)
        else:
          G.add_edge(v1,v2,capacity=1)
         
  flow_value, flow_dict = nx.maximum_flow(G, "source", "sink")

  for v1 in flow_dict.keys():
    if v1 in ('sink','source'):continue
    for v2 in flow_dict[v1].keys():
      if v2 in ('sink','source'):continue
      if flow_dict[v1][v2]:
        i1,j1 = divmod(v1,M)
        i2,j2 = divmod(v2,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(flow_value)
  for i in range(N):
    print(''.join(S[i]))
    
if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

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.DiGraph()
  G.add_node('source')
  G.add_node('sink')
  dx,dy=(1,0),(0,1)
  for i in range(N):
    for j in range(M):
      if S[i][j]=='#':continue
      if (i+j) %2:
        G.add_edge(index(i,j),'sink',capacity=1)
      else:
        G.add_edge('source',index(i,j),capacity=1)
      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:
          G.add_edge(v2,v1,capacity=1)
        else:
          G.add_edge(v1,v2,capacity=1)

  flow_value, flow_dict = nx.maximum_flow(G, "source", "sink")

  for v1 in flow_dict.keys():
    if v1 in ('sink','source'):continue
    for v2 in flow_dict[v1]:
      if v2 in ('sink','source'):continue
      if flow_dict[v1][v2]:
        i1,j1 = divmod(v1,M)
        i2,j2 = divmod(v2,M)
        (i1,j1),(i2,j2) = sorted([(i1,j1),(i2,j2)])
        if i1 + 1 == i2:
          S[i1][j1] = 'v'
          S[i2][j2] = '^'
        else:
          S[i1][j1] = '>'
          S[i2][j2] = '<'

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

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx

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.DiGraph()
G.add_node('source')
G.add_node('sink')
dx,dy=(1,0),(0,1)
for i in range(N):
  for j in range(M):
    if S[i][j]=='#':continue
    if (i+j) %2:
      G.add_edge(index(i,j),'sink',capacity=1)
    else:
      G.add_edge('source',index(i,j),capacity=1)
    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:
        G.add_edge(v2,v1,capacity=1)
      else:
        G.add_edge(v1,v2,capacity=1)
        
flow_value, flow_dict = nx.maximum_flow(G, "source", "sink")

for v1 in flow_dict.keys():
  if v1 in ('sink','source'):continue
  for v2 in flow_dict[v1]:
    if v2 in ('sink','source'):continue
    if flow_dict[v1][v2]:
      i1,j1 = divmod(v1,M)
      i2,j2 = divmod(v2,M)
      (i1,j1),(i2,j2) = sorted([(i1,j1),(i2,j2)])
      if i1 + 1 == i2:
        S[i1][j1] = 'v'
        S[i2][j2] = '^'
      else:
        S[i1][j1] = '>'
        S[i2][j2] = '<'

print(flow_value)
for i in range(N):
  print(''.join(S[i]))

Submission status: Time Limit Exceeded

Solution code:
from networkx import*

N, M = map(int, input().split())
A = [[a for a in input()] for _ in range(N)]
X = [[1 if a == "." else 0 for a in aa] for aa in A]
G = DiGraph()
G.add_nodes_from(range(N * M + 2))
s = N * M
t = s + 1
for i in range(N):
    for j in range(M):
        if X[i][j]:
            if (i ^ j) & 1 == 0:
                G.add_edge(s, i * M + j, capacity = 1)
            else:
                G.add_edge(i * M + j, t, capacity = 1)

for i in range(N - 1):
    for j in range(M):
        if X[i][j] and X[i+1][j]:
            a = i * M + j
            b = a + M
            if (i ^ j) & 1 == 0:
                G.add_edge(a, b, capacity = 1)
            else:
                G.add_edge(b, a, capacity = 1)
for i in range(N):
    for j in range(M - 1):
        if X[i][j] and X[i][j+1]:
            a = i * M + j
            b = a + 1
            if (i ^ j) & 1 == 0:
                G.add_edge(a, b, capacity = 1)
            else:
                G.add_edge(b, a, capacity = 1)

ans, mf = maximum_flow(G, s, t)
for a in mf:
    for b in mf[a]:
        v = mf[a][b]
        if v:
            if a >= N * M or b >= N * M: continue
            aa, bb = (a, b) if a < b else (b, a)
            i, j = aa // M, aa % M
            ii, jj = bb // M, bb % M
            if i == ii:
                A[i][j] = ">"
                A[ii][jj] = "<"
            else:
                A[i][j] = "v"
                A[ii][jj] = "^"

print(ans)
for x in A:
    print("".join(map(str, x)))

Submission status: Time Limit Exceeded

Solution code:
from networkx import*

N, M = map(int, input().split())
A = [[a for a in input()] for _ in range(N)]
X = [[1 if a == "." else 0 for a in aa] for aa in A]
G = DiGraph()
G.add_nodes_from(range(N * M + 2))
s = N * M
t = s + 1
for i in range(N):
    for j in range(M):
        if X[i][j]:
            if (i ^ j) & 1 == 0:
                G.add_edge(s, i * M + j, capacity = 1)
            else:
                G.add_edge(i * M + j, t, capacity = 1)

for i in range(N - 1):
    for j in range(M):
        if X[i][j] and X[i+1][j]:
            a = i * M + j
            b = a + M
            if (i ^ j) & 1 == 0:
                G.add_edge(a, b, capacity = 1)
            else:
                G.add_edge(b, a, capacity = 1)
for i in range(N):
    for j in range(M - 1):
        if X[i][j] and X[i][j+1]:
            a = i * M + j
            b = a + 1
            if (i ^ j) & 1 == 0:
                G.add_edge(a, b, capacity = 1)
            else:
                G.add_edge(b, a, capacity = 1)

ans, mf = maximum_flow(G, s, t)
for a in mf:
    for b in mf[a]:
        if a >= N * M or b >= N * M: continue
        v = mf[a][b]
        if v:
            aa, bb = (a, b) if a < b else (b, a)
            i, j = aa // M, aa % M
            ii, jj = bb // M, bb % M
            if i == ii:
                A[i][j] = ">"
                A[ii][jj] = "<"
            else:
                A[i][j] = "v"
                A[ii][jj] = "^"

print(ans)
for x in A:
    print("".join(map(str, x)))

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
INF = 10**9
import sys
sys.setrecursionlimit(6000)
G = [[] for _ in range(n*m+2)]

def add_edge(s, t, cap):
    G[s].append([t, cap, len(G[t])])
    G[t].append([s, 0, len(G[s])-1])

def get_edges(s):
    pass

def dfs(v, t, f, used):
    """ 増加パスをDFSで探す、再帰バージョン
    Args:
        v (int): 探索の開始地点
        t (int): 探索の終了地点
        f (int): 流す量
        used (list): 訪れた点の記録
    Returns:
        int: 流すことのできた量
    """
    if v == t:
        return f
    used[v] = 1
    for idx, (nn, cap, rev) in enumerate(G[v]):
        if used[nn] == 0 and cap > 0:
            d = dfs(nn, t, min(f, cap), used)
            if d > 0:
                G[v][idx][1] -= d
                G[nn][rev][1] += d
                return d
    else:
        return 0

def flow(s, t):
    ans = 0
    while True:
        used = [0] * (n*m+2)
        f = dfs(s, t, INF, used)
        if f == 0:
            return ans
        ans += f


S = [list(input()) for _ in range(n)]

# n*mを始点, n*m+1を終点とする
for i, line in enumerate(S):
    for j, s in enumerate(line):
        cp = i*m+j
        if (i%2 == 0 and j%2 == 0) or (i%2 == 1 and j%2 == 1):
            if s == '.':
                add_edge(n*m, cp, 1)
                for mi, mj in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
                    ni, nj = i+mi, j+mj
                    if 0 <= ni < n and 0 <= nj < m and S[ni][nj] == '.':
                        ep = ni*m+nj
                        add_edge(cp, ep, 1)
        else:
            if s == '.':
                add_edge(cp, n*m+1, 1)

f = flow(n*m, n*m+1)
print(f)

for a, cap, rev in G[n*m]:
    if cap == 0:
        for b, cap, rev in G[a]:
            if cap == 0:
                # a to b
                i, j = divmod(a, m)
                ii, jj = divmod(b, m)
                np = ii - i, jj - j
                if np == (1, 0):
                    S[i][j] = 'v'
                    S[ii][jj] = '^'
                elif np == (-1, 0):
                    S[i][j] = '^'
                    S[ii][jj] = 'v'
                elif np == (0, 1):
                    S[i][j] = '>'
                    S[ii][jj] = '<'
                elif np == (0, -1):
                    S[i][j] = '<'
                    S[ii][jj] = '>'
                break

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

Submission status: Accepted

Solution code:
from collections import deque
N,M=map(int,input().split())
S=[list(input()) for i in range(N)]
V=N*M+2
G=[[] for i in range(V)]
L=[0]*V
I=[0]*V
INF=10**15
def ae(fr,to,ca):
  global G
  G[fr].append([to,ca,len(G[to]),0])
  G[to].append([fr,0,len(G[fr])-1,0])

def bfs(s):
  global INF,L,V,G
  L=[-1]*V
  Q=deque()
  L[s]=0
  Q.append(s)
  while(len(Q)):
    x=Q.popleft()
    for i in range(len(G[x])):
      if G[x][i][1]>0 and L[G[x][i][0]]<0:
        L[G[x][i][0]]=L[x]+1
        Q.append(G[x][i][0]) 

def dfs(v,t,f):
  global I,G,V
  if v==t:
    return f
  for i in range(I[v],len(G[v])):
    if G[v][i][1]>0 and L[v]<L[G[v][i][0]]:
      d=dfs(G[v][i][0],t,min(f,G[v][i][1]))
      if d>0:
        G[v][i][1]-=d
        G[v][i][3]+=d
        G[G[v][i][0]][G[v][i][2]][1]+=d
        G[G[v][i][0]][G[v][i][2]][3]-=d
        return d
    I[v]+=1
  return 0

def mf(s,t):
  global L,I,INF,V
  fl=0
  while(True):
    bfs(s)
    if L[t]<0:
      break
    I=[0]*V
    f=0
    while(True):
      f=dfs(s,t,INF)
      if f<=0:
        break
      fl+=f
  return fl

w4x=[0,1,0,-1]
w4y=[1,0,-1,0]
v=0
for i in range(N):
  for j in range(M):
    if (i+j)&1:
      ae(i*M+j,V-1,1)
      continue
    ae(V-2,i*M+j,1)
    if S[i][j]=='#':
      continue
    for k in range(4):
      v=[i+w4y[k],j+w4x[k]]
      if min(v)<0 or v[0]==N or v[1]==M:
        continue
      if S[v[0]][v[1]]=='.':
        ae(i*M+j,v[0]*M+v[1],1)
print(mf(V-2,V-1))
for i in range(N*M):
  for j in range(len(G[i])):
    if G[i][j][3]>0:
      v=G[i][j][0]
      if v>=N*M:
        continue
      if i+M==v:
        S[i//M][i%M]='v'
        S[i//M+1][i%M]='^'
      elif i-M==v:
        S[i//M-1][i%M]='v'
        S[i//M][i%M]='^'
      elif i+1==v:
        S[i//M][i%M]='>'
        S[i//M][i%M+1]='<'
      elif i-1==v:
        S[i//M][i%M-1]='>'
        S[i//M][i%M]='<'
for i in range(N):
  print(''.join(S[i]))

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/practice2/submissions/16598132
# 上記のリンクの提出をいじらせてもらってます。

class mf_graph:

    def __init__(self, N):
        self.N = N
        self.graph = [[] for _ in range(N)]
        self.capacities = [dict() for _ in range(N)]

    def add_edge(self, v, w, cap):
        self.graph[v].append(w)
        self.graph[w].append(v)
        if w in self.capacities[v]:
            self.capacities[v][w] += cap
        else:
            self.capacities[v][w] = cap
        if v not in self.capacities[w]:
            self.capacities[w][v] = 0

    def bfs(self, s, t):
        self.level = [-1] * self.N
        q = [s]
        self.level[s] = 0
        while q:
            nq = []
            for v in q:
                for w, cap in self.capacities[v].items():
                    if cap and self.level[w] == -1:
                        self.level[w] = self.level[v] + 1
                        if w == t:
                            return True
                        nq.append(w)
            q = nq
        return False

    def dfs(self, s, t, up):
        st = [t]
        while st:
            v = st[-1]
            if v == s:
                flow = up
                for i in range(len(st) - 2):
                    if flow > self.capacities[st[i + 1]][st[i]]:
                        flow = self.capacities[st[i+1]][st[i]]
                for i in range(len(st) - 1):
                    self.capacities[st[i]][st[i+1]] += flow
                    self.capacities[st[i+1]][st[i]] -= flow
                return flow
            while self.it[v] < len(self.graph[v]):
                w = self.graph[v][self.it[v]]
                cap = self.capacities[w][v]
                if cap and self.level[w] != -1:
                    if self.level[v] > self.level[w]:
                        st.append(w)
                        break
                self.it[v] += 1
            else:
                st.pop()
                self.level[v] = self.N
        return 0

    def flow(self, s, t, flow_limit=float('inf')):
        flow = 0
        while flow < flow_limit and self.bfs(s, t):
            self.it = [0]*self.N
            while flow < flow_limit:
                f = self.dfs(s, t, flow_limit - flow)
                if not f:
                    break
                flow += f
        return flow

    def min_cut(self, s):
        visited = [False]*self.N
        q = [s]
        while q:
            v = q.pop()
            visited[v] = True
            for w, cap in self.capacities[v].items():
                if cap and not visited[w]:
                    q.append(w)


# """
N, M = map(int, input().split())
S = [list(input()) for i in range(N)]
"""
with open("flow.txt") as f:
    N, M = map(int, f.readline().rstrip().split())
    S = [list(f.readline().rstrip()) for i in range(N)]
#"""
dc = mf_graph(N*M+2)

s = N*M
t = N*M+1
for i in range(N):
    for j in range(M):
        if (i+j) % 2 == 0:
            dc.add_edge(s, M*i+j, 1)
        else:
            dc.add_edge(M*i+j, t, 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)

print(dc.flow(s, t, N * M))
for u in range(N*M+2):
    ui, uj = divmod(u, M)
    if (ui+uj) % 2 == 1:
        continue
    for v, cap in dc.capacities[u].items():
        if cap != 0:
            continue
        vi, vj = divmod(v, M)
        if u != s and u != t and v != s and v != t:
            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] = ">"

for res in S:
    print("".join(res))

Submission status: Accepted

Solution code:
# thanks: https://atcoder.jp/contests/practice2/submissions/16784996

#!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify

import itertools
import math, fractions
import sys, copy

def L(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline().rstrip())
def SL(): return list(sys.stdin.readline().rstrip())
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def R(n): return [sys.stdin.readline().strip() for _ in range(n)]
def LR(n): return [L() for _ in range(n)]
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def LIR1(n): return [LI1() for _ in range(n)]
def SLR(n): return [SL() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]

def perm(n, r): return math.factorial(n) // math.factorial(r)
def comb(n, r): return math.factorial(n) // (math.factorial(r) * math.factorial(n-r))

def make_list(n, *args, default=0): return [make_list(*args, default=default) for _ in range(n)] if args else [default for _ in range(n)]

dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
alphabets = "abcdefghijklmnopqrstuvwxyz"
ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
MOD = 1000000007
INF = float("inf")

sys.setrecursionlimit(1000000)

class MaxFlowGraph:
    def __init__(self, N):
        self.N = N
        self.graph = [[] for _ in range(N)]
        self.paths = []
        self.capacities = [dict() for _ in range(N)]

    def add_edge(self, v, w, cap=1):
        self.graph[v].append(w)
        self.graph[w].append(v)
        self.capacities[v][w] = cap
        self.capacities[w][v] = 0

    def dinic_bfs(self, s, t):
        self.level = [-1] * self.N
        q = deque([s])
        self.level[s] = 0
        while q:
            v = q.popleft()
            for w, cap in self.capacities[v].items():
                if cap and self.level[w] == -1:
                    self.level[w] = self.level[v] + 1
                    if w == t: return True
                    q.append(w)
        return False

    def dinic_dfs(self, s, t, limit):
        st = [t]
        while st:
            v = st[-1]
            if v == s: break
            #vから行ける全ての頂点について
            while self.it[v] < len(self.graph[v]):
                # w -> v の cap
                w = self.graph[v][self.it[v]]
                cap = self.capacities[w][v]
                if cap and self.level[w] != -1 and self.level[v] > self.level[w]:
                    st.append(w)
                    break
                self.it[v] += 1
            else:
                st.pop()
                self.level[v] = self.N
        else: return 0

        flow = min(limit, min(self.capacities[st[i + 1]][st[i]] for i in range(len(st) - 2)))
        for i in range(len(st) - 1):
            self.capacities[st[i]][st[i+1]] += flow
            self.capacities[st[i+1]][st[i]] -= flow
        self.paths.append(st)
        return flow

    def dinic_flow(self, s, t, flow_limit=18446744073709551615):
        flow = 0
        while flow < flow_limit and self.dinic_bfs(s, t):
            self.it = [0]*self.N
            while flow < flow_limit:
                f = self.dinic_dfs(s, t, flow_limit - flow)
                if not f: break
                flow += f
        return flow

    def min_cut(self, s):
        visited = [False]*self.N
        q = [s]
        while q:
            v = q.pop()
            visited[v] = True
            for w, cap in self.capacities[v].items():
                if cap and not visited[w]:
                    q.append(w)

def main():
    N, M = LI()
    S = SLR(N)
    g = MaxFlowGraph(N*M+2)

    s = N*M
    t = N*M+1

    # 偶数はblack, 奇数はwhiteとして市松模様に塗る、二部グラフの最大マッチング問題
    # s -> black -> white -> t の辺を張って最大流を求める
    for y in range(N):
        for x in range(M):
            # black
            if (y+x) % 2 == 0:
                g.add_edge(s, M*y+x)
                for dy, dx in [[1, 0], [0, 1]]:
                    ny, nx = y + dy, x + dx
                    if 0 <= ny < N and 0 <= nx < M and S[y][x] == "." and S[ny][nx] == ".":
                        g.add_edge(M*y+x, M*ny+nx)
            # white
            else:
                g.add_edge(M*y+x, t)
                for dy, dx in [[1, 0], [0, 1]]:
                    ny, nx = y + dy, x + dx
                    if 0 <= ny < N and 0 <= nx < M and S[y][x] == "." and S[ny][nx] == ".":
                        g.add_edge(M*ny+nx, M*y+x)

    print(g.dinic_flow(s, t))
    # print(paths)
    # for path in g.paths:
    #     u, v = path[1:-1]
    #     uy, ux = divmod(u, M)
    #     vy, vx = divmod(v, M)
    #     if uy - 1 == vy:
    #         S[uy][ux], S[vy][vx] = "^", "v"
    #     elif uy + 1 == vy:
    #         S[uy][ux], S[vy][vx] = "v", "^"
    #     elif ux + 1 == vx:
    #         S[uy][ux], S[vy][vx] = ">", "<"
    #     elif ux - 1 == vx:
    #         S[uy][ux], S[vy][vx] = "<", ">"
    # for p in S:
    #     print("".join(p))

    # blackから考える
    for u in range(N*M+2):
        uy, ux = divmod(u, M)
        if (uy + ux) % 2 == 1: continue

        for v, cap in g.capacities[u].items():
            if cap != 0: continue
            vy, vx = divmod(v, M)
            if u != s and u != t and v != s and v != t:
                if uy - 1 == vy:
                    S[uy][ux], S[vy][vx] = "^", "v"
                elif uy + 1 == vy:
                    S[uy][ux], S[vy][vx] = "v", "^"
                elif ux + 1 == vx:
                    S[uy][ux], S[vy][vx] = ">", "<"
                elif ux - 1 == vx:
                    S[uy][ux], S[vy][vx] = "<", ">"

    for p in S:
        print("".join(p))



if __name__ == '__main__':
    main()