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: Runtime Error

Solution code:
import networkx as nx

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

index = lambda i,j: i*M+j

G=nx.DiGraph()
dx,dy=(1,0),(0,1)
for i in range(N):
  for j in range(M):
    if S[i][j]=='#':continue
    if (i+j) %2:
      G.add_edge(index(i,j),'sink',capacity=1)
    else:
      G.add_edge('source',index(i,j),capacity=1)
    for k in range(2):
      v1,v2 = index(i,j),index(i+dx[k],j+dy[k])
      if not (0<=i+dx[k]<N and 0<=j+dy[k]<M):
        continue
      if S[i+dx[k]][j+dy[k]] == '#': continue
      if (i+j) % 2:
        G.add_edge(v2,v1,capacity=1)
      else:
        G.add_edge(v1,v2,capacity=1)
        
flow_value, flow_dict = nx.maximum_flow(G, "source", "sink")

ans = [list(S[i]) for i in range(N)]
for v1 in flow_dict.keys():
  if v1 in ('sink','source'):continue
  for v2 in flow_dict[v1]:
    if v2 in ('sink','source'):continue
    if flow_dict[v1][v2]:
      i1,j1 = divmod(v1,M)
      i2,j2 = divmod(v2,M)
      (i1,j1),(i2,j2) = sorted([(i1,j1),(i2,j2)])
      if i1 + 1 == i2:
        ans[i1][j1] = 'v'
        ans[i2][j2] = '^'
      else:
        ans[i1][j1] = '>'
        ans[i2][j2] = '<'

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

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline


class FordFulkerson:
    def __init__(self, n):
        self.n = n
        self.graph = [[] for _ in range(n)]
        self.ans = dict()
        
    #二頂点間を結ぶ経路の追加
    def add_edge(self, fr, to, cap):
        forward = [to, cap, None]
        forward[2] = backward = [fr, cap, forward]
        self.graph[fr].append(forward)
        self.graph[to].append(backward)

    #二頂点間を結ぶ経路の追加（ただし距離が異なる：単方向とかはこれで実装） 
    def add_multi_edge(self, v1, v2, cap1, cap2):
        edge1 = [v2, cap1, None]
        edge1[2] = edge2 = [v1, cap2, edge1]
        self.graph[v1].append(edge1)
        self.graph[v2].append(edge2)
    
    def dfs(self, v, t, f, start, end):
        if v == t:
            return f
        used = self.used
        used[v] = 1
        for e in self.graph[v]:
            w, cap, rev = e
            if cap and not used[w]:
                d = self.dfs(w, t, min(f, cap), start, end)
                if d:
                    e[1] -= d
                    rev[1] += d
                    self.ans[w] = rev[0]
                    return d
        return 0
    

    def flow(self, s, t):
        flow = 0
        f = INF = 10**9 + 7
        N = self.n
        while f:
            self.used = [0]*N
            f = self.dfs(s, t, INF, s, t)
            flow += f
        return flow


def main():
    n, m = map(int, input().split())
    s = [[1 if x == "#" else 0 for x in input()[:-1]] for i in range(n)]
    
    flow = FordFulkerson(n*m+2)
    start = 0
    end = n*m+1
    direction = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    for i in range(n):
        for j in range(m):
            if s[i][j] == 0:
                if (i+j)%2:
                    flow.add_edge(start, i*n+j+1, 1)
                    for x, y in direction:
                        ni, nj = x + i, y + j
                        if 0 <= ni < n and 0 <= nj < m and s[ni][nj] == 0:
                            flow.add_edge(i*n+j+1, ni*n+nj+1, 1)
                else:
                    flow.add_edge(i*n+j+1, end, 1)
    

    res = flow.flow(start, end)
    print(res)

    ans = [["#" if s[i][j] else "." for j in range(n)] for i in range(n)]

    flow_list = dict()
    for g in flow.graph:
        for node in g:
            fr, to = node[0], node[2][0]
            if fr == start or fr == end or to == start or to == end:
                continue
            cap = node[1]
            if cap != 1:
                fr, to = min(fr, to)-1, max(fr, to)-1
                flow_list[fr] = to
            
    for k, v in flow_list.items():
        if m > 1 and v-k == 1:
            ans[k//n][k%n] = ">"
            ans[v//n][v%n] = "<"
        else:
            ans[k//n][k%n] = "v"
            ans[v//n][v%n] = "^"


    for a in ans:
        print("".join(a))


    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import networkx as nx

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

index = lambda i,j: i*M+j

G=nx.DiGraph()
dx,dy=(1,0),(0,1)
for i in range(N):
  for j in range(M):
    if S[i][j]=='#':continue
    if (i+j) %2:
      G.add_edge(index(i,j),'sink',capacity=1)
    else:
      G.add_edge('source',index(i,j),capacity=1)
    for k in range(2):
      v1,v2 = index(i,j),index(i+dx[k],j+dy[k])
      if not (0<=i+dx[k]<N and 0<=j+dy[k]<M):
        continue
      if S[i+dx[k]][j+dy[k]] == '#': continue
      if (i+j) % 2:
        G.add_edge(v2,v1,capacity=1)
      else:
        G.add_edge(v1,v2,capacity=1)
        
flow_value, flow_dict = nx.maximum_flow(G, "source", "sink")

ans = [list(S[i]) for i in range(N)]
for v1 in flow_dict.keys():
  if v1 in ('sink','source'):continue
  for v2 in flow_dict[v1]:
    if v2 in ('sink','source'):continue
    if flow_dict[v1][v2]:
      i1,j1 = divmod(v1,N)
      i2,j2 = divmod(v2,N)
      (i1,j1),(i2,j2) = sorted([(i1,j1),(i2,j2)])
      if i1 + 1 == i2:
        ans[i1][j1] = 'v'
        ans[i2][j2] = '^'
      else:
        ans[i1][j1] = '>'
        ans[i2][j2] = '<'
        
for i in range(N):
  print(''.join(ans[i]))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline


class FordFulkerson:
    def __init__(self, n):
        self.n = n
        self.graph = [[] for _ in range(n)]
        self.ans = dict()
        
    #二頂点間を結ぶ経路の追加
    def add_edge(self, fr, to, cap):
        forward = [to, cap, None]
        forward[2] = backward = [fr, cap, forward]
        self.graph[fr].append(forward)
        self.graph[to].append(backward)

    #二頂点間を結ぶ経路の追加（ただし距離が異なる：単方向とかはこれで実装） 
    def add_multi_edge(self, v1, v2, cap1, cap2):
        edge1 = [v2, cap1, None]
        edge1[2] = edge2 = [v1, cap2, edge1]
        self.graph[v1].append(edge1)
        self.graph[v2].append(edge2)
    
    def dfs(self, v, t, f, start, end):
        if v == t:
            return f
        used = self.used
        used[v] = 1
        for e in self.graph[v]:
            w, cap, rev = e
            if cap and not used[w]:
                d = self.dfs(w, t, min(f, cap), start, end)
                if d:
                    e[1] -= d
                    rev[1] += d
                    self.ans[w] = rev[0]
                    return d
        return 0
    

    def flow(self, s, t):
        flow = 0
        f = INF = 10**9 + 7
        N = self.n
        while f:
            self.used = [0]*N
            f = self.dfs(s, t, INF, s, t)
            flow += f
        return flow


def main():
    n, m = map(int, input().split())
    s = [[1 if x == "#" else 0 for x in input()[:-1]] for i in range(n)]
    
    flow = FordFulkerson(n*m+2)
    start = 0
    end = n*m+1
    direction = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    for i in range(n):
        for j in range(m):
            if s[i][j] == 0:
                if (i+j)%2:
                    flow.add_edge(start, i*n+j+1, 1)
                    for x, y in direction:
                        ni, nj = x + i, y + j
                        if 0 <= ni < n and 0 <= nj < m and s[ni][nj] == 0:
                            flow.add_edge(i*n+j+1, ni*n+nj+1, 1)
                else:
                    flow.add_edge(i*n+j+1, end, 1)
    

    res = flow.flow(start, end)
    print(res)

    judge1 = set()
    judge2 = set()
    for k, v in flow.ans.items():
        if v == start or v == end or k == start or k == end:
            continue
        judge1.add(k)
        judge2.add(v)
    
    not_use = set()
    for k in judge1:
        if k in judge2 and flow.ans[k] in judge1:
            not_use.add(k)

    for i in range(n):
        for j in range(m):
            if s[i][j] == 1:
                s[i][j] = "#"
            if s[i][j] == 0:
                s[i][j] = "."

    for k in judge1:
        if k in not_use:
            continue
        v = flow.ans[k]
        p, q = min(k, v)-1, max(k, v)-1
        if m > 1 and q - p == 1:
            s[p//n][p%n] = ">"
            s[q//n][q%n] = "<"
        else:
            s[p//n][p%n] = "v"
            s[q//n][q%n] = "^"
    

    for ans in s:
        print("".join(ans))





    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
readline = sys.stdin.readline
import collections
class Dinic:
    def __init__(self, vnum):
        self.edge = [[] for i in range(vnum)]
        self.n = vnum
        # infはint型の方が良いかもね
        self.inf = float('inf')
    def addedge(self, st, en, c):
        self.edge[st].append([en, c, len(self.edge[en])])
        self.edge[en].append([st, 0, len(self.edge[st])-1])
    def bfs(self, vst):
        dist = [-1]*self.n
        dist[vst] = 0
        Q = collections.deque([vst])
        while Q:
            nv = Q.popleft()
            for vt, c, r in self.edge[nv]:
                if dist[vt] == -1 and c > 0:
                    dist[vt] = dist[nv] + 1
                    Q.append(vt)
        self.dist = dist
    def dfs(self, nv, en, nf):
        nextv = self.nextv
        if nv == en:
            return nf
        dist = self.dist
        ist = nextv[nv]
        for i, (vt, c, r) in enumerate(self.edge[nv][ist:], ist):
            if dist[nv] < dist[vt] and c > 0:
                df = self.dfs(vt, en, min(nf, c))
                if df > 0:
                    self.edge[nv][i][1] -= df
                    self.edge[vt][r][1] += df
                    return df
            nextv[nv] += 1
        return 0
    def getmf(self, st, en):
        mf = 0
        while True:
            self.bfs(st)
            if self.dist[en] == -1:
                break
            self.nextv = [0]*self.n
            while True:
                fl = self.dfs(st, en, self.inf)
                if fl > 0:
                    mf += fl
                else:
                    break
        return mf


N, M = map(int, readline().split())

G = [[1 if s == '#' else 0 for s in readline().strip()] for _ in range(N)]

T = Dinic(2*N*M+2)
st = 2*N*M
en = st+1
geta = N*M
DIREC = ((1, 0), (-1, 0), (0, 1), (0, -1))


for i in range(N):
    for j in range(M):
        if not G[i][j]:
            if (i+j)%2:
                T.addedge(st, i*N+j, 1)
                for di, dj in DIREC:
                    ni, nj = i+di, j+dj
                    if 0 <= ni < N and 0 <= nj < M and not G[ni][nj]:
                        T.addedge(i*N+j, geta + ni*N+nj, 1)
            else:
                T.addedge(geta + i*N+j, en, 1)

print(T.getmf(st, en))

Ans = [g[:] for g in G]

for i in range(N):
    for j in range(M):
        if not (i+j)%2 and not G[i][j]:
            for vf, c, _ in T.edge[geta + N*i+j]:
                if c == 1 and vf != en:
                    ni, nj = divmod(vf, N)
                    if i == ni:
                        if j < nj:
                            Ans[i][j] = 2
                            Ans[ni][nj] = 3
                        else:
                            Ans[i][j] = 3
                            Ans[ni][nj] = 2
                    else:
                        if i < ni:
                            Ans[i][j] = 4
                            Ans[ni][nj] = 5
                        else:
                            Ans[i][j] = 5
                            Ans[ni][nj] = 4

D = ['.', '#', '>', '<', 'v', '^']

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