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:
# -*- coding: utf-8 -*-
# import bisect
# import heapq
# import math
# import random
# from collections import Counter, defaultdict, deque
# from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
# from fractions import Fraction
# from functools import lru_cache, reduce
# from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
# from operator import add, mul, sub, itemgetter, attrgetter
import queue

import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


class Dinic:
    def __init__(self, v):
        self.V = v
        self.G = [list() for _ in range(v)]
        self.level = [0 for _ in range(v)]
        self.iter = [0 for _ in range(v)]
        self.pos = []

    def add_edge(self, from_, to, cap):
        self.pos.append((from_, len(self.G[from_])))
        # to: 行き先, cap: 容量, rev: 反対側の辺
        # 0           1          2
        self.G[from_].append([to, cap, len(self.G[to])])
        self.G[to].append([from_, 0, len(self.G[from_])-1])


    def edges(self):
        es = []
        for f, t in self.pos:
            e = self.G[f][t]
            re = self.G[e[0]][e[2]]
            # from, to, cap, flow
            e = [f, e[0], e[1] + re[1], re[1]]
            es.append(e)
        return es

    # sからの最短距離をbfsで計算
    def bfs(self, s):
        self.level = [-1 for _ in range(self.V)]
        self.level[s] = 0
        que = queue.Queue()
        que.put(s)
        while not que.empty():
            v = que.get()
            for i in range(len(self.G[v])):
                e = self.G[v][i]
                if e[1] > 0 and self.level[e[0]] < 0:
                    self.level[e[0]] = self.level[v] + 1
                    que.put(e[0])

    # 増加バスをdfsで探す
    def dfs(self, v, t, f):
        if v == t:
            return f
        for i in range(self.iter[v], len(self.G[v])):
            self.iter[v] = i
            e = self.G[v][i]
            if e[1] > 0 and self.level[v] < self.level[e[0]]:
                d = self.dfs(e[0], t, min(f, e[1]))
                if d > 0:
                    e[1] -= d
                    self.G[e[0]][e[2]][1] += d
                    return d

        return 0

    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            # bfsで到達不可
            if self.level[t] < 0:
                return flow
            self.iter = [0 for _ in range(self.V)]
            f = self.dfs(s, t, INF)
            while f > 0:
                flow += f
                f = self.dfs(s, t, INF)


@mt
def slv(N, M, S):
    S = [list(s) for s in S]
    g = Dinic(N*M+2)
    s = N*M
    t = s + 1

    for i in range(N):
        for j in range(M):
            if S[i][j] == '#':
                continue
            v = i*M + j
            if (i + j )%2 == 0:
                g.add_edge(s, v, 1)
            else:
                g.add_edge(v, t, 1)



    for i in range(N):
        for j in range(M):
            if S[i][j] == '#':
                continue
            if (i+j) % 2 == 1:
                continue
            v0 = i*M + j
            for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
                if not (0 <= x < N and 0 <= y < M):
                    continue
                v1 = x*M + y
                g.add_edge(v0, v1, 1)

    print(g.max_flow(s, t))
    for from_, to, _, flow in g.edges():
        if from_ in {s, t} or to in {s, t} or flow == 0:
            continue
        i0 = from_ // M
        j0 = from_ % M
        i1 = to // M
        j1 = to % M

        if i0 == i1+1:
            S[i1][j1] = 'v'
            S[i0][j0] = '^'
        elif j0 == j1+1:
            S[i1][j1] = '>'
            S[i0][j0] = '<'
        elif i0 == i1-1:
            S[i1][j1] = '^'
            S[i0][j0] = 'v'
        else:
            S[i1][j1] = '<'
            S[i0][j0] = '>'

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


def main():
    N, M = read_int_n()
    S = [read_str() for _ in range(N)]
    slv(N, M, S)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter
import queue

import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


class Dinic:
    def __init__(self, v):
        self.V = v
        self.G = [list() for _ in range(v)]
        self.level = [0 for _ in range(v)]
        self.iter = [0 for _ in range(v)]
        self.pos = []

    def add_edge(self, from_, to, cap):
        self.pos.append((from_, len(self.G[from_])))
        # to: 行き先, cap: 容量, rev: 反対側の辺
        # 0           1          2
        self.G[from_].append([to, cap, len(self.G[to])])
        self.G[to].append([from_, 0, len(self.G[from_])-1])


    def edges(self):
        es = []
        for f, t in self.pos:
            e = self.G[f][t]
            re = self.G[e[0]][e[2]]
            # from, to, cap, flow
            e = [f, e[0], e[1] + re[1], re[1]]
            es.append(e)
        return es

    # sからの最短距離をbfsで計算
    def bfs(self, s):
        self.level = [-1 for _ in range(self.V)]
        self.level[s] = 0
        que = queue.Queue()
        que.put(s)
        while not que.empty():
            v = que.get()
            for i in range(len(self.G[v])):
                e = self.G[v][i]
                if e[1] > 0 and self.level[e[0]] < 0:
                    self.level[e[0]] = self.level[v] + 1
                    que.put(e[0])

    # 増加バスをdfsで探す
    def dfs(self, v, t, f):
        if v == t:
            return f
        for i in range(self.iter[v], len(self.G[v])):
            self.iter[v] = i
            e = self.G[v][i]
            if e[1] > 0 and self.level[v] < self.level[e[0]]:
                d = self.dfs(e[0], t, min(f, e[1]))
                if d > 0:
                    e[1] -= d
                    self.G[e[0]][e[2]][1] += d
                    return d

        return 0

    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            # bfsで到達不可
            if self.level[t] < 0:
                return flow
            self.iter = [0 for _ in range(self.V)]
            f = self.dfs(s, t, INF)
            while f > 0:
                flow += f
                f = self.dfs(s, t, INF)


@mt
def slv(N, M, S):
    S = [list(s) for s in S]
    g = Dinic(N*M+2)
    s = N*M
    t = s + 1

    for i in range(N):
        for j in range(M):
            if S[i][j] == '#':
                continue
            v = i*M + j
            if (i + j )%2 == 0:
                g.add_edge(s, v, 1)
            else:
                g.add_edge(v, t, 1)

    for i in range(N):
        for j in range(M):
            if S[i][j] == '#':
                continue
            if (i+j) % 2 == 1:
                continue
            v0 = i*M + j
            for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
                if not (0 <= x < N and 0 <= y < M):
                    continue
                v1 = x*M + y
                g.add_edge(v0, v1, 1)

    print(g.max_flow(s, t))
    for from_, to, _, flow in g.edges():
        if from_ in {s, t} or to in {s, t} or flow == 0:
            continue
        i0 = from_ // M
        j0 = from_ % M
        i1 = to // M
        j1 = to % M

        if i0 == i1+1:
            S[i1][j1] = 'v'
            S[i0][j0] = '^'
        elif j0 == j1+1:
            S[i1][j1] = '>'
            S[i0][j0] = '<'
        elif i0 == i1-1:
            S[i1][j1] = '^'
            S[i0][j0] = 'v'
        else:
            S[i1][j1] = '<'
            S[i0][j0] = '>'

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


def main():
    N, M = read_int_n()
    S = [read_str() for _ in range(N)]
    slv(N, M, S)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter
import queue

import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


class Dinic:
    def __init__(self, v):
        self.V = v
        self.G = [list() for _ in range(v)]
        self.level = [0 for _ in range(v)]
        self.iter = [0 for _ in range(v)]
        self.pos = []

    def add_edge(self, from_, to, cap):
        self.pos.append((from_, len(self.G[from_])))
        # to: 行き先, cap: 容量, rev: 反対側の辺
        # 0           1          2
        self.G[from_].append([to, cap, len(self.G[to])])
        self.G[to].append([from_, 0, len(self.G[from_])-1])


    def edges(self):
        es = []
        for f, t in self.pos:
            e = self.G[f][t]
            re = self.G[e[0]][e[2]]
            e = {
                'from': f,
                'to': e[0],
                'cap': e[1] + re[1],
                'flow': re[1]
            }
            es.append(e)
        return es

    # sからの最短距離をbfsで計算
    def bfs(self, s):
        self.level = [-1 for _ in range(self.V)]
        self.level[s] = 0
        que = queue.Queue()
        que.put(s)
        while not que.empty():
            v = que.get()
            for i in range(len(self.G[v])):
                e = self.G[v][i]
                if e[1] > 0 and self.level[e[0]] < 0:
                    self.level[e[0]] = self.level[v] + 1
                    que.put(e[0])

    # 増加バスをdfsで探す
    def dfs(self, v, t, f):
        if v == t:
            return f
        for i in range(self.iter[v], len(self.G[v])):
            self.iter[v] = i
            e = self.G[v][i]
            if e[1] > 0 and self.level[v] < self.level[e[0]]:
                d = self.dfs(e[0], t, min(f, e[1]))
                if d > 0:
                    e[1] -= d
                    self.G[e[0]][e[2]][1] += d
                    return d

        return 0

    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            # bfsで到達不可
            if self.level[t] < 0:
                return flow
            self.iter = [0 for _ in range(self.V)]
            f = self.dfs(s, t, INF)
            while f > 0:
                flow += f
                f = self.dfs(s, t, INF)


@mt
def slv(N, M, S):
    S = [list(s) for s in S]
    g = Dinic(N*M+2)
    s = N*M
    t = s + 1

    for i in range(N):
        for j in range(M):
            if S[i][j] == '#':
                continue
            v = i*M + j
            if (i + j )%2 == 0:
                g.add_edge(s, v, 1)
            else:
                g.add_edge(v, t, 1)

    for i in range(N):
        for j in range(M):
            if S[i][j] == '#':
                continue
            if (i+j) % 2 == 1:
                continue
            v0 = i*M + j
            for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
                if not (0 <= x < N and 0 <= y < M):
                    continue
                v1 = x*M + y
                g.add_edge(v0, v1, 1)

    print(g.max_flow(s, t))
    for e in g.edges():
        if e['from'] in {s, t} or e['to'] in {s, t} or e['flow'] == 0:
            continue
        i0 = e['from'] // M
        j0 = e['from'] % M
        i1 = e['to'] // M
        j1 = e['to'] % M

        if i0 == i1+1:
            S[i1][j1] = 'v'
            S[i0][j0] = '^'
        elif j0 == j1+1:
            S[i1][j1] = '>'
            S[i0][j0] = '<'
        elif i0 == i1-1:
            S[i1][j1] = '^'
            S[i0][j0] = 'v'
        else:
            S[i1][j1] = '<'
            S[i0][j0] = '>'

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

    # return ans


def main():
    N, M = read_int_n()
    S = [read_str() for _ in range(N)]
    slv(N, M, S)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter
import queue

import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


class Dinic:
    def __init__(self, v, inf=sys.maxsize):
        self.V = v
        self.inf = inf
        self.G = [list() for _ in range(v)]
        self.level = [0 for _ in range(v)]
        self.iter = [0 for _ in range(v)]
        self.pos = []

    def add_edge(self, from_, to, cap):
        # to: 行き先, cap: 容量, rev: 反対側の辺
        self.pos.append((from_, len(self.G[from_])))
        self.G[from_].append({'to': to, 'cap': cap, 'rev': len(self.G[to])})
        self.G[to].append({'to': from_, 'cap': 0, 'rev': len(self.G[from_])-1})


    def edges(self):
        es = []
        for f, t in self.pos:
            e = self.G[f][t]
            re = self.G[e['to']][e['rev']]
            e = {
                'from': f,
                'to': e['to'],
                'cap': e['cap'] + re['cap'],
                'flow': re['cap']
            }
            es.append(e)
        return es

    # sからの最短距離をbfsで計算
    def bfs(self, s):
        self.level = [-1 for _ in range(self.V)]
        self.level[s] = 0
        que = queue.Queue()
        que.put(s)
        while not que.empty():
            v = que.get()
            for i in range(len(self.G[v])):
                e = self.G[v][i]
                if e['cap'] > 0 and self.level[e['to']] < 0:
                    self.level[e['to']] = self.level[v] + 1
                    que.put(e['to'])

    # 増加バスをdfsで探す
    def dfs(self, v, t, f):
        if v == t:
            return f
        for i in range(self.iter[v], len(self.G[v])):
            self.iter[v] = i
            e = self.G[v][i]
            if e['cap'] > 0 and self.level[v] < self.level[e['to']]:
                d = self.dfs(e['to'], t, min(f, e['cap']))
                if d > 0:
                    e['cap'] -= d
                    self.G[e['to']][e['rev']]['cap'] += d
                    return d

        return 0

    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            # bfsで到達不可
            if self.level[t] < 0:
                return flow
            self.iter = [0 for _ in range(self.V)]
            f = self.dfs(s, t, self.inf)
            while f > 0:
                flow += f
                f = self.dfs(s, t, self.inf)


@mt
def slv(N, M, S):
    S = [list(s) for s in S]
    g = Dinic(N*M+2, inf=INF)
    s = N*M
    t = s + 1

    for i in range(N):
        for j in range(M):
            if S[i][j] == '#':
                continue
            v = i*M + j
            if (i + j )%2 == 0:
                g.add_edge(s, v, 1)
            else:
                g.add_edge(v, t, 1)

    for i in range(N):
        for j in range(M):
            if S[i][j] == '#':
                continue
            if (i+j) % 2 == 1:
                continue
            v0 = i*M + j
            for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
                if not (0 <= x < N and 0 <= y < M):
                    continue
                v1 = x*M + y
                g.add_edge(v0, v1, 1)

    print(g.max_flow(s, t))
    for e in g.edges():
        if e['from'] in {s, t} or e['to'] in {s, t} or e['flow'] == 0:
            continue
        i0 = e['from'] // M
        j0 = e['from'] % M
        i1 = e['to'] // M
        j1 = e['to'] % M

        if i0 == i1+1:
            S[i1][j1] = 'v'
            S[i0][j0] = '^'
        elif j0 == j1+1:
            S[i1][j1] = '>'
            S[i0][j0] = '<'
        elif i0 == i1-1:
            S[i1][j1] = '^'
            S[i0][j0] = 'v'
        else:
            S[i1][j1] = '<'
            S[i0][j0] = '>'

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

    # return ans


def main():
    N, M = read_int_n()
    S = [read_str() for _ in range(N)]
    slv(N, M, S)


if __name__ == '__main__':
    main()

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

G = nx.DiGraph()
G.add_nodes_from(['S', 'T'])
for i, j in itertools.product(range(N), range(M)):
    if S[i, j] == '#':
        continue
    if (i + j) % 2 == 0:
        G.add_edge('S', (i, j), capacity=1)
    else:
        G.add_edge((i, j), 'T', capacity=1)
    if (i + j) % 2 == 0:
        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] != '#':
                G.add_edge((i, j), (i1, j1), capacity=1)

flow_value, flow = nx.maximum_flow(G, 'S', 'T')
for i, j in itertools.product(range(N), range(M)):
    if (i, j) in flow:
        for v, f in flow[(i, j)].items():
            if v == 'T' or f == 0:
                continue
            i1, j1 = v
            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(flow_value)
for row in S:
    print(''.join(row))

Submission status: Accepted

Solution code:
import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10**9)
INF = 10**19
MOD = 10**9 + 7
EPS = 10**-10

def build_grid(H, W, intv, _type, space=False, padding=True):
    # 入力がスペース区切りかどうか
    if space:
        _input = lambda: input().split()
    else:
        _input = lambda: input()
    _list = lambda: list(map(_type, _input()))
    # 余白の有無
    if padding:
        offset = 1
    else:
        offset = 0
    grid = list2d(H+offset*2, W+offset*2, intv)
    for i in range(offset, H+offset):
        row = _list()
        for j in range(offset, W+offset):
            grid[i][j] = row[j-offset]
    return grid

class Dinic:
    """ 最大流(Dinic)：O(E*V^2) """

    INF = 10**18

    def __init__(self, n):
        self.n = n
        self.links = [[] for _ in range(n)]
        self.depth = None
        self.progress = None
        self.pos = []

    def copy(self):
        res = Dinic(self.n)
        res.links = [[a[:] for a in b] for b in self.links]
        res.pos = [a[:] for a in self.pos]
        return res

    def add_edge(self, _from, to, cap):
        self.pos.append((_from, len(self.links[_from])))
        self.links[_from].append([cap, to, len(self.links[to])])
        self.links[to].append([0, _from, len(self.links[_from]) - 1])

    def bfs(self, s):
        from collections import deque

        depth = [-1] * self.n
        depth[s] = 0
        q = deque([s])
        while q:
            v = q.popleft()
            for cap, to, _ in self.links[v]:
                if cap > 0 and depth[to] < 0:
                    depth[to] = depth[v] + 1
                    q.append(to)
        self.depth = depth

    def dfs(self, v, t, flow):
        if v == t:
            return flow
        links_v = self.links[v]
        for i in range(self.progress[v], len(links_v)):
            self.progress[v] = i
            cap, to, rev = link = links_v[i]
            if cap == 0 or self.depth[v] >= self.depth[to]:
                continue
            d = self.dfs(to, t, min(flow, cap))
            if d == 0:
                continue
            link[0] -= d
            self.links[to][rev][0] += d
            return d
        return 0

    def flow(self, s, t):
        INF = Dinic.INF
        flow = 0
        while True:
            self.bfs(s)
            if self.depth[t] < 0:
                return flow
            self.progress = [0] * self.n
            current_flow = self.dfs(s, t, INF)
            while current_flow > 0:
                flow += current_flow
                current_flow = self.dfs(s, t, INF)

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

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

N, M = MAP()
grid = build_grid(N, M, '#', str)
N += 2; M += 2

dinic = Dinic(N*M+2)
s = N*M
t = N*M + 1

directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
for i in range(1, N-1):
    for j in range(1, M-1):
        if grid[i][j] == '#':
            continue
        u = M*i + j
        if (i+j) % 2 == 1:
            # 始点 -> 各マス
            dinic.add_edge(s, u, 1)
            for di, dj in directions:
                ni, nj = i+di, j+dj
                if grid[ni][nj] == '.':
                    v = M*ni + nj
                    # 各マス -> 4方向
                    dinic.add_edge(u, v, 1)
        else:
            # 各マス -> 終点
            dinic.add_edge(u, t, 1)

res = dinic.flow(s, t)
edges = dinic.get_edges()
for u, v, cap, f in edges:
    if u != s and v != t and f:
        ci, cj = divmod(u, M)
        ni, nj = divmod(v, M)
        if ci+1 == ni:
            grid[ci][cj] = 'v'
            grid[ni][nj] = '^'
        elif ci == ni+1:
            grid[ci][cj] = '^'
            grid[ni][nj] = 'v'
        elif cj+1 == nj:
            grid[ci][cj] = '>'
            grid[ni][nj] = '<'
        elif cj == nj+1:
            grid[ci][cj] = '<'
            grid[ni][nj] = '>'

print(res)
for i in range(1, N-1):
    print(''.join(grid[i][1:M-1]))

Submission status: Accepted

Solution code:
import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10**9)
INF = 10**19
MOD = 10**9 + 7
EPS = 10**-10

def build_grid(H, W, intv, _type, space=False, padding=True):
    # 入力がスペース区切りかどうか
    if space:
        _input = lambda: input().split()
    else:
        _input = lambda: input()
    _list = lambda: list(map(_type, _input()))
    # 余白の有無
    if padding:
        offset = 1
    else:
        offset = 0
    grid = list2d(H+offset*2, W+offset*2, intv)
    for i in range(offset, H+offset):
        row = _list()
        for j in range(offset, W+offset):
            grid[i][j] = row[j-offset]
    return grid

class Dinic:
    """ 最大流(Dinic)：O(E*V^2) """

    INF = 10**18

    def __init__(self, n):
        self.n = n
        self.links = [[] for _ in range(n)]
        self.depth = None
        self.progress = None
        self.pos = []

    def copy(self):
        res = Dinic(self.n)
        res.links = [[a[:] for a in b] for b in self.links]
        res.pos = [a[:] for a in self.pos]
        return res

    def add_edge(self, _from, to, cap):
        self.pos.append((_from, len(self.links[_from])))
        self.links[_from].append([cap, to, len(self.links[to])])
        self.links[to].append([0, _from, len(self.links[_from]) - 1])

    def bfs(self, s):
        from collections import deque

        depth = [-1] * self.n
        depth[s] = 0
        q = deque([s])
        while q:
            v = q.popleft()
            for cap, to, _ in self.links[v]:
                if cap > 0 and depth[to] < 0:
                    depth[to] = depth[v] + 1
                    q.append(to)
        self.depth = depth

    def dfs(self, v, t, flow):
        if v == t:
            return flow
        links_v = self.links[v]
        for i in range(self.progress[v], len(links_v)):
            self.progress[v] = i
            cap, to, rev = link = links_v[i]
            if cap == 0 or self.depth[v] >= self.depth[to]:
                continue
            d = self.dfs(to, t, min(flow, cap))
            if d == 0:
                continue
            link[0] -= d
            self.links[to][rev][0] += d
            return d
        return 0

    def flow(self, s, t):
        INF = Dinic.INF
        flow = 0
        while True:
            self.bfs(s)
            if self.depth[t] < 0:
                return flow
            self.progress = [0] * self.n
            current_flow = self.dfs(s, t, INF)
            while current_flow > 0:
                flow += current_flow
                current_flow = self.dfs(s, t, INF)

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

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

N, M = MAP()
grid = build_grid(N, M, '#', str)
N += 2; M += 2

dinic = Dinic(N*M+2)
s = N*M
t = N*M + 1

directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
for i in range(1, N-1):
    for j in range(1, M-1):
        if grid[i][j] == '#':
            continue
        u = M*i + j
        if (i+j) % 2 == 1:
            dinic.add_edge(s, u, 1)
            for di, dj in directions:
                ni, nj = i+di, j+dj
                v = M*ni + nj
                if grid[ni][nj] == '.':
                    dinic.add_edge(u, v, 1)
        else:
            dinic.add_edge(u, t, 1)

res = dinic.flow(s, t)
edges = dinic.get_edges()
for u, v, cap, f in edges:
    if u not in [s, t] and v not in [s, t] and f:
        ci, cj = divmod(u, M)
        ni, nj = divmod(v, M)
        if ci+1 == ni:
            grid[ci][cj] = 'v'
            grid[ni][nj] = '^'
        elif ci == ni+1:
            grid[ci][cj] = '^'
            grid[ni][nj] = 'v'
        elif cj+1 == nj:
            grid[ci][cj] = '>'
            grid[ni][nj] = '<'
        elif cj == nj+1:
            grid[ci][cj] = '<'
            grid[ni][nj] = '>'

print(res)
for i in range(1, N-1):
    print(''.join(grid[i][1:M-1]))