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:
# 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 = [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=18446744073709551615):
        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)

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)


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

    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: Accepted

Solution code:
# Reference: https://tjkendev.github.io/procon-library/python/max_flow/dinic.html

from collections import deque
from sys import setrecursionlimit
setrecursionlimit(10**9)

class Dinic:
    def __init__(self, n):
        self.n = n
        self.G = [[] for _ in range(n)]

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

    def bfs(self, source, sink):
        self.level = level = [None] * self.n
        deq = deque([source])
        level[source] = 0
        G = self.G
        while deq:
            v = deq.popleft()
            lv = level[v] + 1
            for w, cap, _ in G[v]:
                if cap and level[w] is None:
                    level[w] = lv
                    deq.append(w)
        return level[sink] is not None

    def dfs(self, v, sink, f):
        if v == sink:
            return f
        level = self.level
        for edge in self.it[v]:
            w, cap, rev = edge
            if cap and level[v] < level[w]:
                d = self.dfs(w, sink, min(f, cap))
                if d:
                    edge[1] -= d
                    rev[1] += d
                    return d
        return 0

    def flow(self, source, sink, inf=2**63 - 1):
        flow = 0
        G = self.G
        while self.bfs(source, sink):
            *self.it, = map(iter, self.G)
            f = inf
            while f:
                f = self.dfs(source, sink, inf)
                flow += f
        return flow

######

from sys import stdin
def input():
    return stdin.readline().strip()

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

    dnc = Dinic(n * m + 2)
    source = n * m
    sink = n*m + 1

    # add edges
    # from even ((i + j) % 2 == 0) to odd ((i + j) % 2 == 1)
    # (i, j) → m*i + j
    d = ((1, 0), (-1, 0), (0, 1), (0, -1))
    for i in range(n):
        for j in range(m):
            if s[i][j] == '#':
                continue

            ind = m*i + j

            if (i + j) % 2 == 0:
                dnc.add_edge(source, ind, 1)
                for dx, dy in d:
                    if 0 <= i + dx < n and 0 <= j + dy < m and s[i+dx][j+dy] == '.':
                        dnc.add_edge(ind, m*(i+dx) + j+dy, 1)
            else:
                dnc.add_edge(ind, sink, 1)

    # flow
    print(dnc.flow(source, sink))

    # rewrite the graph
    for ind in range(n * m):
        i, j = divmod(ind, m)

        if (i + j) % 2 == 1:
            continue

        for v, cap, rev in dnc.G[ind]:
            if v == source or v == sink or rev[1] == 0:
                continue

            x, y = divmod(v, m)

            if i + 1 == x:
                s[i][j] = 'v'
                s[x][y] = '^'
            elif i - 1 == x:
                s[i][j] = '^'
                s[x][y] = 'v'
            elif j + 1 == y:
                s[i][j] = '>'
                s[x][y] = '<'
            else:
                s[i][j] = '<'
                s[x][y] = '>'

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

main()

Submission status: Accepted

Solution code:
import sys
from collections import deque
from copy import deepcopy
sys.setrecursionlimit(10**7)
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし


class Dinic:
    def __init__(self, N):
        self.N = N
        self.G = [[] for _ in range(N)]

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

    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, t):
        self.level = level = [None]*self.N
        deq = deque([s])
        level[s] = 0
        G = self.G
        while deq:
            v = deq.popleft()
            lv = level[v] + 1
            for w, cap, _ in G[v]:
                if cap and level[w] is None:
                    level[w] = lv
                    deq.append(w)
        return level[t] is not None

    def dfs(self, v, t, f):
        if v == t:
            return f
        level = self.level
        for e in self.it[v]:
            w, cap, rev = e
            if cap and level[v] < level[w]:
                d = self.dfs(w, t, min(f, cap))
                if d:
                    e[1] -= d
                    rev[1] += d
                    return d
        return 0

    def flow(self, s, t):
        flow = 0
        INF = 10**9 + 7
        G = self.G
        while self.bfs(s, t):
            *self.it, = map(iter, self.G)
            f = INF
            while f:
                f = self.dfs(s, t, INF)
                flow += f
        return flow


N,M = MI()
S = [LS2() for _ in range(N)]

D = Dinic(N*M+2)
s,t = N*M,N*M+1
for i in range(N):
    for j in range(M):
        if (i+j) % 2 == 0:
            D.add_edge(s,M*i+j,1)
        else:
            D.add_edge(M*i+j,t,1)

for i in range(N-1):
    for j in range(M):
        if S[i][j] == S[i+1][j] == '.':
            a,b = M*i+j,M*(i+1)+j
            if (i+j) % 2 == 1:
                a,b = b,a
            D.add_edge(a,b,1)

for i in range(N):
    for j in range(M-1):
        if S[i][j] == S[i][j+1] == '.':
            a,b = M*i+j,M*i+(j+1)
            if (i+j) % 2 == 1:
                a,b = b,a
            D.add_edge(a,b,1)

print(D.flow(s,t))

ANS = deepcopy(S)
for a in range(N*M):
    for b,cap,_ in D.G[a]:
        if b == s or b == t:
            continue
        ai,aj = divmod(a,M)
        bi,bj = divmod(b,M)
        if (ai+aj) % 2 == 0 and cap == 0:
            if ai+1 == bi:
                ANS[ai][aj] = 'v'
                ANS[bi][bj] = '^'
            elif ai == bi+1:
                ANS[ai][aj] = '^'
                ANS[bi][bj] = 'v'
            elif aj+1 == bj:
                ANS[ai][aj] = '>'
                ANS[bi][bj] = '<'
            elif aj == bj+1:
                ANS[ai][aj] = '<'
                ANS[bi][bj] = '>'

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

Submission status: Accepted

Solution code:
import sys
from collections import deque

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


class Dinic:
    def __init__(self, N):
        self.N = N
        self.G = [[] for _ in range(N)]

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

    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, t):
        self.level = [None] * self.N
        self.level[s] = 0
        que = deque([s])
        G = self.G
        while que:
            v = que.popleft()
            next_level = self.level[v] + 1
            for w, cap, _ in G[v]:
                if cap and self.level[w] is None:
                    self.level[w] = next_level
                    que.append(w)
        return self.level[t] is not None

    def dfs(self, v, t, f):
        if v == t:
            return f
        level = self.level
        for e in self.it[v]:
            w, cap, rev = e
            if cap and level[v] < level[w]:
                d = self.dfs(w, t, min(f, cap))
                if d:
                    e[1] -= d
                    rev[1] += d
                    return d
        return 0

    def flow(self, s, t):
        flow = 0
        INF = 10 ** 9 + 7
        G = self.G
        while self.bfs(s, t):
            *self.it, = map(iter, self.G)
            f = INF
            while f:
                f = self.dfs(s, t, INF)
                flow += f
        return flow


def resolve():
    n, m = map(int, input().split())
    grid = [list(input().rstrip()) for _ in range(n)]

    mf = Dinic(n * m + 2)
    start = n * m
    end = start + 1

    for i in range(n):
        for j in range(m):
            if grid[i][j] == "#":
                continue
            if (i + j) % 2 == 0:
                mf.add_edge(start, i * m + j, 1)
                for di, dj in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
                    next_i, next_j = i + di, j + dj
                    if next_i < 0 or next_i >= n or next_j < 0 or next_j >= m:
                        continue
                    if grid[next_i][next_j] == "#":
                        continue
                    mf.add_edge(i * m + j, next_i * m + next_j, 1)
            else:
                mf.add_edge(i * m + j, end, 1)

    res = mf.flow(start, end)

    for y in range(n):
        for x in range(m):
            if grid[y][x] == "#" or (y + x) % 2 or (y * m + x) == start or (y * m + x) == end:
                continue
            for to, cap, _ in mf.G[y * m + x]:
                if cap == 0 and to != start and to != end:
                    next_y, next_x = divmod(to, m)
                    if y + 1 == next_y:
                        grid[y][x] = 'v'
                        grid[next_y][next_x] = '^'
                    elif y == next_y + 1:
                        grid[y][x] = '^'
                        grid[next_y][next_x] = 'v'
                    elif x + 1 == next_x:
                        grid[y][x] = '>'
                        grid[next_y][next_x] = '<'
                    elif x == next_x + 1:
                        grid[y][x] = '<'
                        grid[next_y][next_x] = '>'

    print(res)
    print(*[''.join(ret) for ret in grid], sep="\n")


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
import sys
from collections import deque

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


class Dinic:
    def __init__(self, N):
        self.N = N
        self.G = [[] for _ in range(N)]

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

    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, t):
        self.level = [None] * self.N
        self.level[s] = 0
        que = deque([s])
        G = self.G
        while que:
            v = que.popleft()
            next_level = self.level[v] + 1
            for w, cap, _ in G[v]:
                if cap and self.level[w] is None:
                    self.level[w] = next_level
                    que.append(w)
        return self.level[t] is not None

    def dfs(self, v, t, f):
        if v == t:
            return f
        level = self.level
        for e in self.it[v]:
            w, cap, rev = e
            if cap and level[v] < level[w]:
                d = self.dfs(w, t, min(f, cap))
                if d:
                    e[1] -= d
                    rev[1] += d
                    return d
        return 0

    def flow(self, s, t):
        flow = 0
        INF = 10 ** 9 + 7
        G = self.G
        while self.bfs(s, t):
            *self.it, = map(iter, self.G)
            f = INF
            while f:
                f = self.dfs(s, t, INF)
                flow += f
        return flow


def resolve():
    n, m = map(int, input().split())
    grid = [list(input().rstrip()) for _ in range(n)]

    mf = Dinic(n * m + 2)
    start = n * m
    end = start + 1
    
    for i in range(n):
        for j in range(m):
            if grid[i][j] == "#":
                continue
            if (i + j) % 2 == 0:
                mf.add_edge(start, i * m + j, 1)
                for di, dj in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
                    next_i, next_j = i + di, j + dj
                    if next_i < 0 or next_i >= n or next_j < 0 or next_j >= m:
                        continue
                    if grid[next_i][next_j] == "#":
                        continue
                    mf.add_edge(i * m + j, next_i * m + next_j, 1)
            else:
                mf.add_edge(i * m + j, end, 1)

    res = mf.flow(start, end)

    for y in range(n):
        for x in range(m):
            for to, cap, rev in mf.G[y * m + x]:
                next_y, next_x = 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 == next_y:
                        grid[y][x] = 'v'
                        grid[next_y][next_x] = '^'
                    elif y == next_y + 1:
                        grid[y][x] = '^'
                        grid[next_y][next_x] = 'v'
                    elif x + 1 == next_x:
                        grid[y][x] = '>'
                        grid[next_y][next_x] = '<'
                    elif x == next_x + 1:
                        grid[y][x] = '<'
                        grid[next_y][next_x] = '>'

    print(res)
    print(*[''.join(ret) for ret in grid], sep="\n")


if __name__ == '__main__':
    resolve()