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 sys
import itertools
import numpy as np
import networkx as nx

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N, M = map(int, readline().split())
S = np.frombuffer(read(), 'S1').reshape(N, -1)[:, :M].astype('U1')

A = []
B = []
E = []

for i, j in itertools.product(range(N), range(M)):
    if S[i, j] == '#':
        continue
    elif (i + j) & 1:
        A.append((i, j))
    else:
        B.append((i, j))

for i, j in A:
    for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        i1, j1 = i + dx, j + dy
        if 0 <= i1 < N and 0 <= j1 < M and S[i1, j1] != '#':
            E.append(((i, j), (i1, j1)))

G = nx.Graph()
G.add_nodes_from(A, bipartite=0)
G.add_nodes_from(B, bipartite=1)
G.add_edges_from(E)

M = nx.bipartite.maximum_matching(G, A)
for key, item in M.items():
    i, j = key
    i1, j1 = item
    if i1 == i + 1:
        a, b = 'v', '^'
    elif i1 == i - 1:
        a, b = '^', 'v'
    elif j1 == j + 1:
        a, b = '>', '<'
    else:
        a, b = '<', '>'
    S[i, j], S[i1, j1] = a, b

print(len(M) // 2)
for row in S:
    print(''.join(row))

Submission status: Accepted

Solution code:
import sys
import itertools
import numpy as np
import networkx as nx

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N, M = map(int, readline().split())
S = np.frombuffer(read(), 'S1').reshape(N, -1)[:, :M].astype('U1')

A = []
B = []
E = []

for i, j in itertools.product(range(N), range(M)):
    if S[i, j] == '#':
        continue
    elif (i + j) & 1:
        A.append((i, j))
    else:
        B.append((i, j))

for i, j in A:
    for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        i1, j1 = i + dx, j + dy
        if 0 <= i1 < N and 0 <= j1 < M and S[i1, j1] != '#':
            E.append(((i, j), (i1, j1)))

G = nx.Graph()
G.add_nodes_from(A, bipartite=0)
G.add_nodes_from(B, bipartite=1)
G.add_edges_from(E)

M = nx.bipartite.eppstein_matching(G, A)
for key, item in M.items():
    i, j = key
    i1, j1 = item
    if i1 == i + 1:
        a, b = 'v', '^'
    elif i1 == i - 1:
        a, b = '^', 'v'
    elif j1 == j + 1:
        a, b = '>', '<'
    else:
        a, b = '<', '>'
    S[i, j], S[i1, j1] = a, b

print(len(M) // 2)
for row in S:
    print(''.join(row))

Submission status: Accepted

Solution code:
import sys
import itertools
import numpy as np
import networkx as nx

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N, M = map(int, readline().split())
S = np.frombuffer(read(), 'S1').reshape(N, -1)[:, :M].astype('U1')

A = []
B = []
E = []

for i, j in itertools.product(range(N), range(M)):
    if S[i, j] == '#':
        continue
    elif (i + j) & 1:
        A.append((i, j))
    else:
        B.append((i, j))

for i, j in A:
    for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        i1, j1 = i + dx, j + dy
        if 0 <= i1 < N and 0 <= j1 < M and S[i1, j1] != '#':
            E.append(((i, j), (i1, j1)))

G = nx.Graph()
G.add_nodes_from(A, bipartite=0)
G.add_nodes_from(B, bipartite=1)
G.add_edges_from(E)

M = nx.bipartite.maximum_matching(G, A)
for key, item in M.items():
    i, j = key
    i1, j1 = item
    if i1 == i + 1:
        a, b = 'v', '^'
    elif i1 == i - 1:
        a, b = '^', 'v'
    elif j1 == j + 1:
        a, b = '>', '<'
    else:
        a, b = '<', '>'
    S[i, j], S[i1, j1] = a, b

print(len(M) // 2)
for row in S:
    print(''.join(row))

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n,m = list(map(int, input().split()))
s = [input() for _ in range(n)]
# scipyの例
import scipy.sparse
data = []
rs = []
cs = []
def add(i,j,v=1,directed=True):
    rs.append(i)
    cs.append(j)
    data.append(v)
    if not directed:
        rs.append(j)
        cs.append(i)
        data.append(v)
S = n*m
T = n*m+1
for i in range(n):
    for j in range(m):
        if (i+j)%2==0:
            add(S, i*m+j)
        else:
            add(i*m+j, T)
        if s[i][j]=="#":
            continue
        u = i*m + j
        if i>=1:
            v = u-m
            if s[i-1][j]==".":
                if (i+j)%2==1:
                    add(v,u)
                else:
                    add(u,v)
        if j>=1:
            v = u-1
            if s[i][j-1]==".":
                if (i+j)%2==1:
                    add(v,u)
                else:
                    add(u,v)
        
g = scipy.sparse.csr_matrix((data, (rs, cs)), shape=(n*m+2, n*m+2))
ans = scipy.sparse.csgraph.maximum_flow(g, S, T) # 最大流
# 復元
val = [["."]*m for _ in range(n)]
for i in range(n):
    for j in range(m):
        if s[i][j]=="#":
            val[i][j] = "#"
        u = i*m + j
        if i>=1:
            v = u-m
            if ans.residual[u,v]==-1:
                val[i][j] = "^"
                val[i-1][j] = "v"
            elif ans.residual[v,u]==-1:
                val[i][j] = "^"
                val[i-1][j] = "v"
        if j>=1:
            v = u-1
            if ans.residual[u,v]==-1:
                val[i][j] = "<"
                val[i][j-1] = ">"
            elif ans.residual[v,u]==-1:
                val[i][j] = "<"
                val[i][j-1] = ">"
print(ans.flow_value)
write("\n".join(["".join(val[i]) for i in range(n)]))

Submission status: Accepted

Solution code:
import networkx as nx

N, M = map(int, input().split())
S = [list(input()) for i in range(N)]
G = nx.DiGraph() # 有向グラフ
G.add_nodes_from(['S', 'T']) # 'S' -> 'T'のflowを考える

# (i+j)の偶奇でグループ分け
# 偶数のマスは奇数のマスと隣接しており、奇数のますは偶数のマスと隣接している
for i in range(N):
    for j in range(M):
        if S[i][j] == '#':
            continue
        if (i + j) % 2 == 0:
            G.add_edge('S', (i, j), capacity=1) # 偶数のマスは'S'と繋ぐ
            # 隣接する奇数のマスが空なら辺を追加('S' -> 'T'の向きで)
            for di, dj in ((1, 0), (0, 1), (-1, 0), (0, -1)):
                ii = i+di; jj = j+dj
                if 0<=ii<N and 0<=jj<M and S[ii][jj]=='.':
                    G.add_edge((i, j), (ii, jj), capacity=1)
        else:
            G.add_edge((i, j), 'T', capacity=1) # 奇数のマスは'T'と繋ぐ

max_flow, flow = nx.maximum_flow(G, 'S', 'T')
for i in range(N):
    for j in range(M):
        if (i, j) in flow:
            for t, f in flow[(i, j)].items():
                if t == 'T' or f == 0:
                    continue

                ii, jj = t
                if ii == i+1:
                    S[i][j] = 'v'; S[ii][jj] = '^'
                elif ii == i-1:
                    S[i][j] = '^'; S[ii][jj] = 'v'
                elif jj == j+1:
                    S[i][j] = '>'; S[ii][jj] = '<'
                else:
                    S[i][j] = '<'; S[ii][jj] = '>'

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

Submission status: Accepted

Solution code:
import networkx as nx

N, M = map(int, input().split())
S = [list(input()) for i in range(N)]
G = nx.DiGraph() # 有向グラフ
G.add_nodes_from(['S', 'T']) # 'S' -> 'T'のflowを考える

# (i+j)の偶奇でグループ分け
# 偶数のマスは奇数のマスと隣接しており、奇数のますは偶数のマスと隣接している
for i in range(N):
    for j in range(M):
        if S[i][j] == '#':
            continue
        if (i + j) % 2 == 0:
            G.add_edge('S', (i, j), capacity=1) # 偶数のマスは'S'と繋ぐ
            # 隣接する奇数のマスが空なら辺を追加('S' -> 'T'の向きで)
            for di, dj in ((1, 0), (0, 1), (-1, 0), (0, -1)):
                ii = i+di; jj = j+dj
                if 0<=ii<N and 0<=jj<M and S[ii][jj]=='.':
                    G.add_edge((i, j), (ii, jj), capacity=1)
        else:
            G.add_edge((i, j), 'T', capacity=1) # 奇数のマスは'T'と繋ぐ

max_flow, flow = nx.maximum_flow(G, 'S', 'T')
for s in flow:
    if s in {'S', 'T'}:
        continue

    i, j = s
    for t in flow[s]:
        if t == 'T':
            continue

        ii, jj = t
        f = flow[s][t]
        if f:
            if ii == i+1:
                S[i][j] = 'v'; S[ii][jj] = '^'
            elif ii == i-1:
                S[i][j] = '^'; S[ii][jj] = 'v'
            elif jj == j+1:
                S[i][j] = '>'; S[ii][jj] = '<'
            else:
                S[i][j] = '<'; S[ii][jj] = '>'

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

Submission status: Accepted

Solution code:
mod = 1000000007
eps = 10**-9


def main():
    import sys
    input = sys.stdin.readline

    from collections import deque

    class Dinic:
        def __init__(self, N):
            self.N = N
            self.adj = [[] for _ in range(N + 1)]
            self.lv = None
            self.progress = None
            self.inf = 1 << 60

        def add_edge(self, fr, to, cap):
            # [to, cap, rev]
            forward = [to, cap, None]
            backward = forward[2] = [fr, 0, forward]
            self.adj[fr].append(forward)
            self.adj[to].append(backward)

        def bfs(self, s, t):
            que = deque([s])
            lv = [-1] * (self.N + 1)
            lv[s] = 0
            while que:
                v = que.popleft()
                lvv = lv[v]
                for u, cap, _ in self.adj[v]:
                    if cap and lv[u] == -1:
                        que.append(u)
                        lv[u] = lvv + 1
                        if u == t:
                            break
            self.lv = lv

        def dfs(self, s, t, flow):
            st = deque([s])
            st_f = deque([flow])
            while st:
                v = st[-1]
                f = st_f[-1]
                if v == t:
                    for i in range(len(st) - 1, 0, -1):
                        p = st[i - 1]
                        edge = self.adj[p][self.progress[p] - 1]
                        edge[1] -= f
                        edge[2][1] += f
                        v = p
                    return f
                if self.progress[v] == len(self.adj[v]):
                    st.pop()
                    st_f.pop()
                    continue
                else:
                    adj_v = self.adj[v]
                    for i in range(self.progress[v], len(adj_v)):
                        i = self.progress[v]
                        self.progress[v] = i + 1
                        u, cap, rev = adj_v[i]
                        if not cap or self.lv[u] != self.lv[v] + 1:
                            continue
                        else:
                            st.append(u)
                            st_f.append(min(st_f[-1], cap))
                            break

        def max_flow(self, s, t):
            flow = 0
            while True:
                self.bfs(s, t)
                if self.lv[t] < 0:
                    return flow
                self.progress = [0] * (self.N + 1)
                flow_new = self.dfs(s, t, self.inf)
                while flow_new:
                    flow += flow_new
                    flow_new = self.dfs(s, t, self.inf)

    H, W = map(int, input().split())
    grid = [[""] * W for _ in range(H)]
    for h in range(H):
        S = input().rstrip('\n')
        for w in range(W):
            grid[h][w] = S[w]

    D = Dinic(H * W + 2)
    s = H * W + 1
    t = H * W + 2
    dhw = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    for h in range(H):
        for w in range(W):
            if (h+w)%2 == 0:
                D.add_edge(s, h*W + w + 1, 1)
            else:
                D.add_edge(h*W + w + 1, t, 1)
            if grid[h][w] == "." and (h+w)%2 == 0:
                for dh, dw in dhw:
                    h_new, w_new = h+dh, w+dw
                    if 0 <= h_new < H and 0 <= w_new < W:
                        if grid[h_new][w_new] == ".":
                            D.add_edge(h*W + w + 1, h_new*W + w_new + 1, 1)
    flow = D.max_flow(s, t)
    print(flow)
    for h in range(H):
        for w in range(W):
            if (h+w)%2 == 0:
                hw = h*W + w + 1
                for hw_new, cap, _ in D.adj[hw]:
                    if hw_new == s:
                        continue
                    if cap == 0:
                        h_new, w_new = divmod(hw_new - 1, W)
                        if h == h_new:
                            if w < w_new:
                                grid[h][w], grid[h][w_new] = "><"
                            else:
                                grid[h][w_new], grid[h][w] = "><"
                        else:
                            if h < h_new:
                                grid[h][w], grid[h_new][w] = "v^"
                            else:
                                grid[h_new][w], grid[h][w] = "v^"
    for h in range(H):
        print("".join(grid[h]))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

class MaxFlow:
    def __init__(self, n):
        self.n = n
        self.graph = [[] for _ in range(n)]
        self.pos = []

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

    def get_edge(self, idx):
        to, rev, cap = self.graph[self.pos[idx][0]][self.pos[idx][1]]
        rev_to, rev_rev, rev_cap = self.graph[to][rev]
        return rev_to, to, cap + rev_cap, rev_cap

    def edges(self):
        m = len(self.pos)
        for i in range(m):
            yield self.get_edge(i)

    def change_edge(self, idx, new_cap, new_flow):
        to, rev, cap = self.graph[self.pos[idx][0]][self.pos[idx][1]]
        self.graph[self.pos[idx][0]][self.pos[idx][1]][2] = new_cap - new_flow
        self.graph[to][rev][2] = new_flow

    def dfs(self, s, v, up):
        if v == s:
            return up
        res = 0
        lv = self.level[v]
        for i in range(self.iter[v], len(self.graph[v])):
            to, rev, cap = self.graph[v][i]
            if lv <= self.level[to] or self.graph[to][rev][2] == 0:
                continue
            d = self.dfs(s, to, min(up - res, self.graph[to][rev][2]))
            if d <= 0:
                continue
            self.graph[v][i][2] += d
            self.graph[to][rev][2] -= d
            res += d
            if res == up:
                break
            self.iter[v] += 1
        return res

    def max_flow(self, s, t):
        return self.max_flow_with_limit(s, t, 2 ** 63 - 1)

    def max_flow_with_limit(self, s, t, limit):
        flow = 0
        while flow < limit:
            self.level = [-1] * self.n
            self.level[s] = 0
            queue = deque()
            queue.append(s)
            while queue:
                v = queue.popleft()
                for to, rev, cap in self.graph[v]:
                    if cap == 0 or self.level[to] >= 0:
                        continue
                    self.level[to] = self.level[v] + 1
                    if to == t:
                        break
                    queue.append(to)
            if self.level[t] == -1:
                break
            self.iter = [0] * self.n
            while flow < limit:
                f = self.dfs(s, t, limit - flow)
                if not f:
                    break
                flow += f
        return flow

    def min_cut(self, s):
        visited = [0] * self.n
        queue = deque()
        queue.append(s)
        while queue:
            p = queue.popleft()
            visited[p] = True
            for to, rev, cap in self.graph[p]:
                if cap and not visited[to]:
                    visited[to] = True
                    queue.append(to)
        return visited


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

mf = MaxFlow(n * m + 2)

start = n * m
end = n * m + 1
d = [(1,0), (-1,0), (0,1), (0,-1)]

for i in range(n):
    for j in range(m):
        if s[i][j] == '#':
            continue
        else:
            if (i + j) % 2 == 0:
                mf.add_edge(start, i * m + j, 1)

                for i1, j1 in d:
                    if 0 <= i + i1 < n and 0 <= j + j1 < m:
                        if s[i+i1][j+j1] == '.':
                            mf.add_edge(i * m + j, (i+i1) * m + (j+j1), 1)

            else:
                mf.add_edge(i * m + j, end, 1)

print(mf.max_flow(start, end))

for i in range(len(mf.pos)):
    s1, e1, cap, flow = mf.get_edge(i)
    if flow == 0 or s1 == start or e1 == end:
        continue
    else:
        si = s1 // m
        sj = s1 % m
        ei = e1 // m
        ej = e1 % m
        if s1 - e1 == m:
            s[si][sj] = '^'
            s[ei][ej] = 'v'
        elif e1 - s1 == m:
            s[si][sj] = 'v'
            s[ei][ej] = '^'
        elif s1 - e1 == 1:
            s[si][sj] = '<'
            s[ei][ej] = '>'
        elif e1 - s1 == 1:
            s[si][sj] = '>'
            s[ei][ej] = '<'

for i in s:
    for j in i:
        print(j, end = '')
    print()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import deque
from collections import defaultdict
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7

INF = 10 ** 10


def init():
    global edges
    edges = defaultdict(dict)


def add_edge(frm, to, capacity):
    edges[frm][to] = capacity
    edges[to][frm] = 0


def bfs(start, goal):
    """
    update: distance_from_start
    return bool: can reach to goal
    """
    global distance_from_start
    distance_from_start = [-1] * (MAX_VERTEX + 1)
    queue = deque()
    distance_from_start[start] = 0
    queue.append(start)
    while queue and distance_from_start[goal] == -1:
        frm = queue.popleft()
        for to in edges[frm]:
            if edges[frm][to] > 0 and distance_from_start[to] == -1:
                distance_from_start[to] = distance_from_start[frm] + 1
                queue.append(to)

    return distance_from_start[goal] != -1


def dfs(current, goal, flow):
    """
    make flow from `current` to `goal`
    update: capacity of edges, iteration_count
    return: flow (if impossible: 0)
    """
    if current == goal:
        return flow
    i = itertion_count[current]
    while itertion_count[current] < len(edges[current]):
        to = edges_index[current][i]
        capacity = edges[current][to]
        if capacity > 0 and distance_from_start[current] < distance_from_start[to]:
            d = dfs(to, goal, min(flow, capacity))
            if d > 0:
                edges[current][to] -= d
                edges[to][current] += d
                return d
        itertion_count[current] += 1
        i += 1
    return 0


def max_flow(start, goal):
    """
    return: max flow from `start` to `goal`
    """
    global itertion_count, edges_index, original_edges, MAX_VERTEX
    from copy import deepcopy
    original_edges = deepcopy(edges)
    flow = 0
    edges_index = {
        frm: list(edges[frm]) for frm in edges
    }
    MAX_VERTEX = max(edges) if edges else goal
    while bfs(start, goal):
        itertion_count = [0] * (MAX_VERTEX + 1)
        f = dfs(start, goal, INF)
        while f > 0:
            flow += f
            f = dfs(start, goal, INF)
    return flow


def get_flow():
    result = []
    for v in original_edges:
        for u in original_edges[v]:
            if original_edges[v][u] > 0:
                d = original_edges[v][u] - edges[v][u]
                if d > 0:
                    result.append((v, u, d))
    return result


def debug(*x):
    print(*x, file=sys.stderr)


def solve(SOLVE_PARAMS):
    pass


def readMap(H, W, S=1):
    global SENTINEL, HEIGHT, WIDTH
    SENTINEL = S
    HEIGHT = H + SENTINEL * 2
    WIDTH = W + SENTINEL * 2
    data = [0] * (HEIGHT * WIDTH)
    ok = ord(".")
    for i in range(H):
        S = input().strip()
        y = (i + SENTINEL) * WIDTH
        for j in range(W):
            data[y + (j + SENTINEL)] = 1 if S[j] == ok else 0
    return data


def main():
    # parse input
    init()
    N, M = map(int, input().split())
    data = readMap(N, M)
    odd = []
    even = []
    from collections import defaultdict
    tmp_edges = defaultdict(list)
    for i in range(len(data) - WIDTH):
        if not data[i]:
            continue
        y, x = divmod(i, WIDTH)
        if (x + y) % 2:
            odd.append(i)
            isEven = False
        else:
            even.append(i)
            isEven = True
        j = i + 1
        if data[j]:
            if isEven:
                tmp_edges[j].append(i)
            else:
                tmp_edges[i].append(j)

        j = i + WIDTH
        if data[j]:
            if isEven:
                tmp_edges[j].append(i)
            else:
                tmp_edges[i].append(j)

    START = 0
    GOAL = 1
    for v in odd:
        tmp_edges[START].append(v)
    for v in even:
        tmp_edges[v].append(GOAL)

    # compaction
    mapping = {}
    vs = odd + even + [START, GOAL]
    for i, v in enumerate(vs):
        mapping[v] = i

    for v in tmp_edges:
        for u in tmp_edges[v]:
            # add_edge(mapping[v], mapping[u], 1)
            add_edge(v, u, 1)

    # debug("vs", vs)
    # debug("edges", edges)
    # ret = max_flow(mapping[START], mapping[GOAL])
    ret = max_flow(START, GOAL)
    print(ret)

    flow = get_flow()
    # debug("flow", flow)
    outmap = ["." if x else "#" for x in data]
    for v, u, _c in flow:
        # debug("vs, u, v", vs, u, v)
        # u = vs[u]
        # v = vs[v]
        if v == START:
            continue
        if u == GOAL:
            continue
        if u < v:
            u, v = v, u
        if u - v == 1:
            outmap[u] = "<"
            outmap[v] = ">"
        if u - v == WIDTH:
            outmap[u] = "^"
            outmap[v] = "v"

    for y in range(N):
        start = (y + 1) * WIDTH + SENTINEL
        end = start + M
        print("".join(outmap[start:end]))


# tests
T1 = """
3 3
#..
..#
...
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
3
#><
><#
><.
"""


T2 = """
10 10
.#........
#.#.......
.#........
..........
..........
..........
......#...
..........
..........
..........
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
46
.#><><><><
#.#><><><v
v#><><><v^
^><><><v^v
><><><v^v^
><><><^v^v
><><><#^v^
><><><><^v
><><><><v^
><><><><^.
"""

T3 = """
1 5
.....
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
2
><><.
"""

T4 = """
3 1
.
.
.
"""
TEST_T4 = """
>>> as_input(T4)
>>> main()
1
v
^
.
"""

T5 = """
3 1
.
#
.
"""
TEST_T5 = """
>>> as_input(T5)
>>> main()
0
.
#
.
"""

T6 = """
1 3
###
"""
TEST_T6 = """
>>> as_input(T6)
>>> main()
result
"""


def _test():
    import doctest
    doctest.testmod()
    g = globals()
    for k in sorted(g):
        if k.startswith("TEST_"):
            doctest.run_docstring_examples(g[k], g, name=k)


def as_input(s):
    "use in test, use given string as input file"
    import io
    f = io.StringIO(s.strip())
    g = globals()
    g["input"] = lambda: bytes(f.readline(), "ascii")
    g["read"] = lambda: bytes(f.read(), "ascii")


input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read

if sys.argv[-1] == "-t":
    print("testing")
    _test()
    sys.exit()

main()

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)
        self.capacities[v][w] = cap
        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))