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:
# 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.capacities = [defaultdict(int) 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

    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 lookup_flow_path(self, s, t):
        frm = [-2] * self.N
        q = deque([s])
        frm[s] = -1

        while q:
            v = q.popleft()
            for u, cap in self.capacities[v].items():
                if cap and frm[u] == -2:
                    frm[u] = v
                    if u == t: break
                    q.append(u)
            else: continue
            break
        else:
            return []
        # [t, u, v, ..., s]
        ret = [t]
        now = t
        while now != s:
            now = frm[now]
            ret.append(now)
        return ret


    def dfs(self, s, t, up):
        st = [t]
        while st:
            v = st[-1]
            if v == s:
                flow = min(up ,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
                return flow
            #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:
                    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=18446744073709551615):
        current_flow = 0
        path = self.lookup_flow_path(s, t)
        while current_flow < flow_limit and path:
            min_flow = min(flow_limit - current_flow, min(self.capacities[path[i + 1]][path[i]] for i in range(len(path) - 2)))
            for i in range(len(path) - 1):
                self.capacities[path[i]][path[i+1]] += min_flow
                self.capacities[path[i+1]][path[i]] -= min_flow
            current_flow += min_flow
            path = self.lookup_flow_path(s, t)
        return current_flow

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

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.flow(s, t))

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


class MF_graph(object):
    def __init__(self, n):
        self.n = n
        self.g = [[] for _ in range(n)]  # to, rev, cap
        self.pos = []

    def add_edge(self, frm, to, cap):
        m = len(self.pos)
        self.pos.append((frm, len(self.g[frm])))
        self.g[frm].append([to, len(self.g[to]), cap])
        self.g[to].append([frm, len(self.g[frm]) - 1, 0])
        return m

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

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

    def change_edge(self, i, new_cap, new_flow):
        f, s = self.pos[i]
        rf, rs, _ = self.g[f][s]
        self.g[f][s][2] = new_cap - new_flow
        self.g[rf][rs][2] = new_flow

    def flow(self, s, t, flow_limit=10**18):
        self.level = [0] * self.n
        self.iter = [0] * self.n

        def bfs():
            self.level = [-1] * self.n
            self.level[s] = 0
            que = deque([s])
            while que:
                v = que.popleft()
                for u_to, _, u_cap in self.g[v]:
                    if u_cap == 0 or self.level[u_to] >= 0:
                        continue
                    self.level[u_to] = self.level[v] + 1
                    if u_to == t:
                        return
                    que.append(u_to)

        def dfs(v, up):
            if v == s:
                return up
            res = 0
            self.level_v = self.level[v]
            for i in range(self.iter[v], len(self.g[v])):
                u_to, u_rev, _ = self.g[v][i]
                if self.level_v <= self.level[u_to] or self.g[u_to][u_rev][2] == 0:
                    continue
                d = dfs(u_to, min(up - res, self.g[u_to][u_rev][2]))
                if d <= 0:
                    continue
                self.g[v][i][2] += d
                self.g[u_to][u_rev][2] -= d
                res += d
                if res == up:
                    break
            return res

        flow = 0
        while flow < flow_limit:
            bfs()
            if self.level[t] == -1:
                break
            self.iter = [0] * self.n
            while flow < flow_limit:
                f = dfs(t, flow_limit - flow)
                if not f:
                    break
                flow += f
        return flow

    def min_cut(self, s):
        visited = [False] * self.n
        que = deque([s])
        while que:
            v = que.popleft()
            visited[v] = True
            for u_to, _, u_cap in self.g[v]:
                if u_cap and (not visited[u_to]):
                    visited[u_to] = True
                    que.append(u_to)
        return visited


if __name__ == "__main__":
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10 ** 7)

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

    g = MF_graph(N * M + 2)
    source = N * M
    sink = N * M + 1

    for i in range(N):
        for j in range(M):
            if grid[i][j] == "#":
                continue
            v = i * M + j
            if (i + j) % 2 == 0:
                g.add_edge(source, v, 1)
            else:
                g.add_edge(v, sink, 1)

    for i in range(N):
        for j in range(M):
            if (i + j) % 2 or grid[i][j] == "#":
                continue
            v0 = i * M + j
            if i and grid[i - 1][j] == ".":
                v1 = (i - 1) * M + j
                g.add_edge(v0, v1, 1)
            if j and grid[i][j - 1] == ".":
                v1 = i * M + j - 1
                g.add_edge(v0, v1, 1)
            if i + 1 < N and grid[i + 1][j] == ".":
                v1 = (i + 1) * M + j
                g.add_edge(v0, v1, 1)
            if j + 1 < M and grid[i][j + 1] == ".":
                v1 = i * M + j + 1
                g.add_edge(v0, v1, 1)

    res = g.flow(source, sink)

    for frm, to, cap, flow in g.edges():
        if frm == source or to == sink or flow == 0:
            continue
        i0, j0 = divmod(frm, M)
        i1, j1 = divmod(to, M)
        if i0 == i1 + 1:
            grid[i1][j1] = "v"
            grid[i0][j0] = "^"
        elif j0 == j1 + 1:
            grid[i1][j1] = ">"
            grid[i0][j0] = "<"
        elif i0 == i1 - 1:
            grid[i1][j1] = "^"
            grid[i0][j0] = "v"
        else:
            grid[i1][j1] = "<"
            grid[i0][j0] = ">"

    print(res)
    for g in grid:
        print("".join(g))

Submission status: Time Limit Exceeded

Solution code:
class Edge():
    def __init__(self, to, cap, rev=None):
        self.to = to
        self.cap = cap
        self.rev = rev

from collections import deque

class Dinic():
    def __init__(self, n):
        self.n = n
        self.inf = 10**18
        self.graph = [[] for _ in range(self.n)]

    def add(self, fr, to, cap):
        edge = Edge(to, cap)
        rev = Edge(fr, 0)
        edge.rev, rev.rev = rev, edge
        self.graph[fr].append(edge)
        self.graph[to].append(rev)

    def max_flow(self, source, sink):
        flow = 0
        while True:
            queue = deque([source])
            level = [None for _ in range(self.n)]
            level[source] = 0
            while queue:
                node = queue.popleft()
                for edge in self.graph[node]:
                    to = edge.to
                    if edge.cap and level[to] is None:
                        level[to] = level[node] + 1
                        queue.append(to)
            if level[sink] is None: break
            stack = [source]
            par = [None for _ in range(self.n)]
            par[source] = source
            cap = [self.inf for _ in range(self.n)]
            while stack:
                node = stack.pop()
                if node == sink:
                    break
                for edge in self.graph[node]:
                    to = edge.to
                    if edge.cap and level[node] < level[to]:
                        par[to] = node
                        cap[to] = min(edge.cap, cap[node])
                        stack.append(to)
            node = sink
            prev = par[sink]
            delta = cap[sink]
            while node != source:
                for edge in self.graph[prev]:
                    if edge.to == node:
                        edge.cap -= delta
                        edge.rev.cap += delta
                node = prev
                prev = par[node]
            flow += delta
        return flow

import sys
input = sys.stdin.readline

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

d = Dinic(N * M + 2)

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

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

for i in range(N):
    for j in range(M):
        if S[i][j] == '#':
            res[i][j] = '#'
            continue
        if (i + j) % 2 == 0:
            d.add(N * M, i * M + j, 1)
            for k in range(4):
                ni = i + dx[k]
                nj = j + dy[k]
                if 0 <= ni < N and 0 <= nj < M and S[ni][nj] == '.':
                    d.add(i * M + j, ni * M + nj, 1)
        else:
            d.add(i * M + j, N * M + 1, 1)

print(d.max_flow(M * N, M * N + 1))

for i in range(N):
    for j in range(M):
        if S[i][j] == '#' or (i + j) % 2:
            continue
        for edge in d.graph[i * M + j]:
            if edge.to == N * M or edge.cap == 1:
                continue
            ti = edge.to // M
            tj = edge.to % M
            if i + 1 == ti:
                res[i][j] = 'v'
                res[ti][tj] = '^'
            elif j + 1 == tj:
                res[i][j] = '>'
                res[ti][tj] = '<'
            elif i == ti + 1:
                res[i][j] = '^'
                res[ti][tj] = 'v'
            else:
                res[i][j] = '<'
                res[ti][tj] = '>'

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

Submission status: Time Limit Exceeded

Solution code:
class Weigthed_Digraph:
    #入力定義
    def __init__(self,vertex=[]):
        self.vertex=set(vertex)

        self.edge_number=0
        self.vertex_number=len(vertex)

        self.adjacent_out={v:{} for v in vertex} #出近傍(vが始点)
        self.adjacent_in={v:{} for v in vertex} #入近傍(vが終点)

    #頂点の追加
    def add_vertex(self,*adder):
        for v in adder:
            if v not in self.vertex:
                self.adjacent_in[v]={}
                self.adjacent_out[v]={}

                self.vertex_number+=1
                self.vertex.add(v)

    #辺の追加(更新)
    def add_edge(self,From,To,weight=1):
        for v in [From,To]:
            if v not in self.vertex:
                self.add_vertex(v)

        if To not in self.adjacent_in[From]:
            self.edge_number+=1

        self.adjacent_out[From][To]=weight
        self.adjacent_in[To][From]=weight

    #辺を除く
    def remove_edge(self,From,To):
        for v in [From,To]:
            if v not in self.vertex:
                self.add_vertex(v)

        if To in self.adjacent_out[From]:
            del self.adjacent_out[From][To]
            del self.adjacent_in[To][From]
            self.edge_number-=1

    #頂点を除く
    def remove_vertex(self,*vertexes):
        for  v in vertexes:
            if v in self.vertex:
                self.vertex_number-=1

                for u in self.adjacent_out[v]:
                    del self.adjacent_in[u][v]
                    self.edge_number-=1
                del self.adjacent_out[v]

                for u in self.adjacent_in[v]:
                    del self.adjacent_out[u][v]
                    self.edge_number-=1
                del self.adjacent_in[v]

    #Walkの追加
    def add_walk(self,*walk):
        pass

    #Cycleの追加
    def add_cycle(self,*cycle):
        pass

    #頂点の交換
    def __vertex_swap(self,p,q):
        self.vertex.sort()

    #グラフに頂点が存在するか否か
    def vertex_exist(self,v):
        return v in self.vertex

    #グラフに辺が存在するか否か
    def edge_exist(self,From,To):
        if not(self.vertex_exist(From) and self.vertex_exist(To)):
            return False
        return To in self.adjacent_out[From]

    #近傍
    def neighbohood(self,v):
        if not self.vertex_exist(v):
            return []
        return list(self.adjacent[v])

    #出次数
    def out_degree(self,v):
        if not self.vertex_exist(v):
            return 0

        return len(self.adjacent_out[v])

    #入次数
    def in_degree(self,v):
        if not self.vertex_exist(v):
            return 0

        return len(self.adjacent_in[v])

    #次数
    def degree(self,v):
        if not self.vertex_exist(v):
            return 0

        return self.out_degree(v)-self.in_degree(v)

    #頂点数
    def vertex_count(self):
        return len(self.vertex)

    #辺数
    def edge_count(self):
        return self.edge_number

    #頂点vを含む連結成分
    def connected_component(self,v):
        pass

def Flow(D,source,sink,Mode=False):
    """Source sからSink tへの最大流問題を解く.
    Mode:
    True---各頂点の流し方も返す
    False---解答のみ
    """
    s,t=source,sink

    H={v:[] for v in D.vertex}

    for u in D.vertex:
        for v in D.adjacent_out[u]:
            F=[v,D.adjacent_out[u][v],None]
            F[2]=B=[u,0,F]
            H[u].append(F)
            H[v].append(B)

    def dfs(v,t,f):
        if v==t:
            return f

        U[v]=True
        for e in H[v]:
            w,cap,inv=e

            if cap and (not U[w]):
                d=dfs(w,t,min(f,cap))
                if d:
                    e[1]-=d
                    inv[1]+=d
                    return d
        return 0

    inf=float("inf")
    f=inf
    flow=0
    while f:
        U={v:False for v in D.vertex}
        f=dfs(s,t,inf)
        flow+=f

    if Mode:
        R={}
        for v in D.vertex:
            R[v]={}
            for S in H[v]:
                w=S[0]
                if w in D.adjacent_out[v]:
                    R[v][w]=S[-1][1]

        return flow,R
    else:
        return flow

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

def g(c):
    return (c//M+1,c%M+1)
#================================================
N,M=map(int,input().split())
D=Weigthed_Digraph(list(range(M*N)))
D.add_vertex("s","t")

S=["*"*(M+2) for _ in range(N+2)]
for i in range(1,N+1):
    S[i]="*"+input()+"*"

H=[(1,0),(-1,0),(0,1),(0,-1)]
for y in range(1,N+1):
    for x in range(1,M+1):
        if S[y][x]!=".":
            continue

        if (x+y)%2:
            D.add_edge("s",f(y,x),1)
            for (a,b) in H:
                if S[y+a][x+b]==".":
                    D.add_edge(f(y,x),f(y+a,x+b),1)
        else:
            D.add_edge(f(y,x),"t",1)

flow,F=Flow(D,"s","t",True)

U=[[S[j][i] for i in range(M+2)] for j in range(N+2)]
for y in range(1,N+1):
    for x in range(1,M+1):
        for C in F[f(y,x)]:
            if isinstance(C,str):
                continue
            elif F[f(y,x)][C]==0:
                continue

            q,p=g(C)
            if (y+1==q) and (x==p):
                alpha,beta="v","^"
            elif (y-1==q) and (x==p):
                alpha,beta="^","v"
            elif (y==q) and (x+1==p):
                alpha,beta=">","<"
            elif (y==q) and (x-1==p):
                alpha,beta="<",">"

            U[y][x]=alpha
            U[q][p]=beta

print(flow)
Y=["".join(T[1:-1]) for T in U[1:-1]]
print("\n".join(Y))

Submission status: Time Limit Exceeded

Solution code:
class Weigthed_Digraph:
    #入力定義
    def __init__(self,vertex=[]):
        self.vertex=set(vertex)

        self.edge_number=0
        self.vertex_number=len(vertex)

        self.adjacent_out={v:{} for v in vertex} #出近傍(vが始点)
        self.adjacent_in={v:{} for v in vertex} #入近傍(vが終点)

    #頂点の追加
    def add_vertex(self,*adder):
        for v in adder:
            if v not in self.vertex:
                self.adjacent_in[v]={}
                self.adjacent_out[v]={}

                self.vertex_number+=1
                self.vertex.add(v)

    #辺の追加(更新)
    def add_edge(self,From,To,weight=1):
        for v in [From,To]:
            if v not in self.vertex:
                self.add_vertex(v)

        if To not in self.adjacent_in[From]:
            self.edge_number+=1

        self.adjacent_out[From][To]=weight
        self.adjacent_in[To][From]=weight

    #辺を除く
    def remove_edge(self,From,To):
        for v in [From,To]:
            if v not in self.vertex:
                self.add_vertex(v)

        if To in self.adjacent_out[From]:
            del self.adjacent_out[From][To]
            del self.adjacent_in[To][From]
            self.edge_number-=1

    #頂点を除く
    def remove_vertex(self,*vertexes):
        for  v in vertexes:
            if v in self.vertex:
                self.vertex_number-=1

                for u in self.adjacent_out[v]:
                    del self.adjacent_in[u][v]
                    self.edge_number-=1
                del self.adjacent_out[v]

                for u in self.adjacent_in[v]:
                    del self.adjacent_out[u][v]
                    self.edge_number-=1
                del self.adjacent_in[v]

    #Walkの追加
    def add_walk(self,*walk):
        pass

    #Cycleの追加
    def add_cycle(self,*cycle):
        pass

    #頂点の交換
    def __vertex_swap(self,p,q):
        self.vertex.sort()

    #グラフに頂点が存在するか否か
    def vertex_exist(self,v):
        return v in self.vertex

    #グラフに辺が存在するか否か
    def edge_exist(self,From,To):
        if not(self.vertex_exist(From) and self.vertex_exist(To)):
            return False
        return To in self.adjacent_out[From]

    #近傍
    def neighbohood(self,v):
        if not self.vertex_exist(v):
            return []
        return list(self.adjacent[v])

    #出次数
    def out_degree(self,v):
        if not self.vertex_exist(v):
            return 0

        return len(self.adjacent_out[v])

    #入次数
    def in_degree(self,v):
        if not self.vertex_exist(v):
            return 0

        return len(self.adjacent_in[v])

    #次数
    def degree(self,v):
        if not self.vertex_exist(v):
            return 0

        return self.out_degree(v)-self.in_degree(v)

    #頂点数
    def vertex_count(self):
        return len(self.vertex)

    #辺数
    def edge_count(self):
        return self.edge_number

    #頂点vを含む連結成分
    def connected_component(self,v):
        pass

def Flow(D,source,sink,Mode=False):
    """Source sからSink tへの最大流問題を解く.
    Mode:
    True---各頂点の流し方も返す
    False---解答のみ
    """
    s,t=source,sink

    H={v:[] for v in D.vertex}

    for u in D.vertex:
        for v in D.adjacent_out[u]:
            F=[v,D.adjacent_out[u][v],None]
            F[2]=B=[u,0,F]
            H[u].append(F)
            H[v].append(B)

    def dfs(v,t,f):
        if v==t:
            return f

        U[v]=True
        for e in H[v]:
            w,cap,inv=e

            if cap and (not U[w]):
                d=dfs(w,t,min(f,cap))
                if d:
                    e[1]-=d
                    inv[1]+=d
                    return d
        return 0

    inf=float("inf")
    f=inf
    flow=0
    while f:
        U={v:False for v in D.vertex}
        f=dfs(s,t,inf)
        flow+=f

    if Mode:
        R={}
        for v in D.vertex:
            R[v]={}
            for S in H[v]:
                w=S[0]
                if w in D.adjacent_out[v]:
                    R[v][w]=S[-1][1]

        return flow,R
    else:
        return flow
#================================================
N,M=map(int,input().split())
D=Weigthed_Digraph([(y,x) for x in range(1,M+1) for y in range(1,N+1)])
D.add_vertex("s","t")

S=["*"*(M+2) for _ in range(N+2)]
for i in range(1,N+1):
    S[i]="*"+input()+"*"

H=[(1,0),(-1,0),(0,1),(0,-1)]
for y in range(1,N+1):
    for x in range(1,M+1):
        if S[y][x]!=".":
            continue

        if (x+y)%2:
            D.add_edge("s",(y,x),1)
            for (a,b) in H:
                if S[y+a][x+b]==".":
                    D.add_edge((y,x),(y+a,x+b),1)
        else:
            D.add_edge((y,x),"t",1)

flow,F=Flow(D,"s","t",True)

U=[[S[j][i] for i in range(M+2)] for j in range(N+2)]
for y in range(1,N+1):
    for x in range(1,M+1):
        for C in F[(y,x)]:
            if isinstance(C,str):
                continue
            elif F[(y,x)][C]==0:
                continue

            q,p=C
            if (y+1==q) and (x==p):
                alpha,beta="v","^"
            elif (y-1==q) and (x==p):
                alpha,beta="^","v"
            elif (y==q) and (x+1==p):
                alpha,beta=">","<"
            elif (y==q) and (x-1==p):
                alpha,beta="<",">"

            U[y][x]=alpha
            U[q][p]=beta

print(flow)
Y=["".join(T[1:-1]) for T in U[1:-1]]
print("\n".join(Y))

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx
from networkx.algorithms.flow import dinitz

n, m = map(int, input().split())

def inside(x, y):
	if 0 <= x < n and 0 <= y < m:
		return True
	else:
		return False

DI = [1, 0, -1, 0]
DJ = [0, 1, 0, -1]

a = [list(input()) for _ in range(n)]
S, T = n*m, n*m+1
g = nx.DiGraph()
g.add_nodes_from(range(n*m+2))
for i in range(n):
	for j in range(m):
		if a[i][j] == "#":
			continue
		if (i+j)%2:
			g.add_edge(i*m+j, T, capacity=1)
		else:
			g.add_edge(S, i*m+j, capacity=1)
			for k in range(4):
				di, dj = i+DI[k], j+DJ[k]
				if inside(di, dj) and a[di][dj] == ".":
					g.add_edge(i*m+j, di*m+dj, capacity=1)
r = dinitz(g, S, T)
print(r.graph["flow_value"])
#print(*r.edges)
for e in r.edges:
	fr, to = e
	#print(fr, to)
	if fr == S or to == T or r[fr][to]["flow"] < 1:
		continue
	i0, j0 = fr//m, fr%m
	i1, j1 = to//m, to%m
	if i1 == i0+1:
		a[i0][j0] = "v"
		a[i1][j1] = "^"
	elif i1 == i0-1:
		a[i0][j0] = "^"
		a[i1][j1] = "v"
	elif j1 == j0+1:
		a[i0][j0] = ">"
		a[i1][j1] = "<"
	else:
		a[i0][j0] = "<"
		a[i1][j1] = ">"
print(*["".join(x) for x in a], sep="\n")