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.#
^><

Solution (Python):




import sys






from collections import Counter, deque, defaultdict


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)


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()

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools


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] == '
                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())

Solution (Python):
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 = [['
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]))

Solution (Python):
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)

    
    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':
    
    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('.

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

Solution (Python):
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]))

Solution (Python):
import sys
readline = sys.stdin.readline
import collections
class Dinic:
    def __init__(self, vnum):
        self.edge = [[] for i in range(vnum)]
        self.n = vnum
        
        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 == '

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 = ['.', '

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

Solution (Python):
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))

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
from heapq import heapify, heappop, heappush
import math
import random
import string
from copy import deepcopy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7





N, M = getNM()
n = N 
m = M 
S = [list(input()) for i in range(N)]


def change(y, x):
    return y * M + (x + 1)

def change_rev(z):
    sz = z - 1
    y_opt = sz // m
    return y_opt, sz - m * y_opt


def change2(y, x):
    return N * M + y * M + (x + 1)

def change2_rev(z):
    sz = z - n * m - 1
    y_opt = sz // m
    return y_opt, sz - m * y_opt

query = []
for i in range(N):
    for j in range(M):
        if S[i][j] == '.':
            query.append([0, change(i, j), 1])
            query.append([change2(i, j), 2 * N * M + 1, 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 == 0:
            continue
        for k in range(4):
            ny = i + dy[k]
            nx = j + dx[k]
            if 0 <= ny < N and 0 <= nx < M and S[i][j] == '.' and S[ny][nx] == '.':
                query.append([change(i, j), change2(ny, nx), 1])

query.sort()

N = 2 * N * M + 2
ans = 0
lines = defaultdict(set)
cost = defaultdict(lambda: defaultdict(int))
for i in range(len(query)):
    a, b, c = query[i]
    if c != 0:
        lines[a].add(b)
        cost[a][b] += c

def Ford_Fulkerson(sta, end):
    global ans
    queue = deque()
    queue.append([sta, float('inf')])

    ignore = [1] * N
    ignore[sta] = 0

    route = [0] * N
    route[sta] = -1

    while queue:
        s, flow = queue.pop()
        for t in lines[s]:  
            if ignore[t]: 
                
                flow = min(cost[s][t], flow)
                route[t] = s
                queue.append([t, flow])
                ignore[t] = 0
                if t == end: 
                    ans += flow
                    break
        else:
            continue 
        
        break
    else:
        return False

    t = end
    s = route[t]
    
    
    while s != -1:
        
        cost[s][t] -= flow
        if cost[s][t] == 0:
            lines[s].remove(t)
            
        if cost[t][s] == 0:
            lines[t].add(s)

        cost[t][s] += flow

        
        t = s
        s = route[t]

    return True

while True:
    
    if Ford_Fulkerson(0, N - 1):
        continue
    else:
        break
cost_aft = deepcopy(cost)
print(ans)
alta = deepcopy(S)

for key, value in cost_aft.items():
    if key == 0 or n * m < key:
        continue
    for k, v in value.items():
        if v == 0:
            sy, sx = change_rev(key)
            ey, ex = change2_rev(k)
            s1y = min(sy, ey)
            e1y = max(sy, ey)
            s1x = min(sx, ex)
            e1x = max(sx, ex)
            if sy == ey:
                alta[s1y][s1x] = '>'
                alta[e1y][e1x] = '<'
            else:
                alta[s1y][s1x] = 'v'
                alta[e1y][e1x] = '^'
for i in alta:
    print(''.join(i))