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:

"""
sから奇数へ，奇数から偶数へ，偶数からtへ
"""
def main():
    # Dinic's algorithm
    import collections
    class Dinic:
        def __init__(self, vnum):
            self.edge = [[] for i in range(vnum)]
            self.n = vnum
            self.inf = 10**10
        def add_edge(self, start, end, c):
            self.edge[start].append([end, c, len(self.edge[end])])
            self.edge[end].append([start, 0, len(self.edge[start])-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 get_max_flow(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
        
    mod=10**9+7
    N,M=map(int, input().split())
    S=[]
    for _ in range(N):
        s=list(input())
        S.append(s)
        
    din=Dinic(N*M+2)
    s=N*M
    t=N*M+1
    
    # 場外との流路
    for i in range(N):
        for j in range(M):
            if S[i][j]=="#":
                continue
            v=M*i + j
            if (i+j)%2==1:
                din.add_edge(s,v,1)
            else:
                din.add_edge(v,t,1)
                
    # 場内
    dx=[0,0,1,-1]
    dy=[1,-1,0,0]
    
    for i in range(N):
        for j in range(M):
            if S[i][j]=="#":
                continue
            v=M*i + j
            if (i+j)%2==1:
                for k in range(4):
                    ni=i+dx[k]
                    nj=j+dy[k]
                    
                    if 0<=ni<N and 0<=nj<M:
                        if S[ni][nj]== "#":
                            continue
                        nv=M*ni + nj
                        din.add_edge(v,nv,1)
                        
    
    ans=din.get_max_flow(s,t)
    
    T=[s[:] for s in S]
            
    
    for v in range(N*M):
        if v%2==1:
            i,j = divmod(v,M)
            if S[i][j]==".":
                for nv,cap,_ in din.edge[v]:
                    if cap==0 and nv!=t:#使った辺を見る
                        ni,nj=divmod(nv,M)
                        # print(i,j," ",ni,nj)
                        if i==ni:
                            if j<nj:
                                T[i][j]=">"
                                T[ni][nj]="<"
                            else:
                                T[i][j]="<"
                                T[ni][nj]=">"
                        else:
                            if i<ni:
                                T[i][j]="v"
                                T[ni][nj]="^"
                            else:
                                T[i][j]="^"
                                T[ni][nj]="v"
                                
                                
    print(ans)
    for i in range(N):
        print(''.join(map(str, T[i])))
                                
                                
                                
            
    
                    
        
    
    

main()

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
sys.setrecursionlimit(100000)
input = sys.stdin.readline


class Dinic:
    def __init__(self, v):
        self.vertice = v
        self.inf = int(1e9)
        self.graph = [[] for i in range(v)]
        self.level = [0]*v
        self.iter = [0]*v
    
    def add_edge(self, fr, to, cap, reverse=True):
        self.graph[fr].append([to, cap, len(self.graph[to])])
        cap2 = cap if reverse else 0
        self.graph[to].append([fr, cap2, len(self.graph[fr])-1])
    
    def bfs(self, s):
        self.level = [-1]*self.vertice
        que = deque([])
        self.level[s] = 0
        que.append(s)

        while que:
            v = que.popleft()
            for i in range(len(self.graph[v])):
                e = self.graph[v][i]
                if e[1] > 0 and self.level[e[0]] < 0:
                    self.level[e[0]] = self.level[v] + 1
                    que.append(e[0])
    
    def dfs(self, v, t, f):
        if v == t:
            return f
        for i in range(self.iter[v], len(self.graph[v])):
            self.iter[v] = i
            e = self.graph[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.graph[e[0]][e[2]][1] += d
                    return d
        return 0
    
    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            if self.level[t] < 0:
                return flow
            self.iter = [0]*self.vertice

            f = self.dfs(s, t, self.inf)
            while f:
                flow += f
                f = self.dfs(s, t, self.inf)
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 = Dinic(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*m+j+1, 1, reverse=False)
                    for x, y in direction:
                        ni, nj = x + i, y + j
                        if 0 <= ni < n and 0 <= nj < m and s[ni][nj] == 0:
                            p, q = min(i*m+j+1, ni*m+nj+1), max(i*m+j+1, ni*m+nj+1)
                            flow.add_edge(p, q, 1, reverse=False)
                else:
                    flow.add_edge(i*m+j+1, end, 1, reverse=False)
    

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

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

    flow_list = []
    for i, g in enumerate(flow.graph):
        for node in g:
            fr, to = i, node[0]
            if fr > to:
                continue
            if fr == start or to == end:
                continue
            cap = node[1]
            if cap == 0:
                flow_list.append((fr-1, to-1))
            
    for k, v in flow_list:
        if v-k == m:
            ans[k//m][k%m] = "v"
            ans[v//m][v%m] = "^"
        else:
            ans[k//m][k%m] = ">"
            ans[v//m][v%m] = "<"

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


    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
sys.setrecursionlimit(100000)
input = sys.stdin.readline


class Dinic:
    def __init__(self, v):
        self.vertice = v
        self.inf = int(1e9)
        self.graph = [[] for i in range(v)]
        self.level = [0]*v
        self.iter = [0]*v
    
    def add_edge(self, fr, to, cap, reverse=True):
        self.graph[fr].append([to, cap, len(self.graph[to])])
        cap2 = cap if reverse else 0
        self.graph[to].append([fr, cap2, len(self.graph[fr])-1])
    
    def bfs(self, s):
        self.level = [-1]*self.vertice
        que = deque([])
        self.level[s] = 0
        que.append(s)

        while que:
            v = que.popleft()
            for i in range(len(self.graph[v])):
                e = self.graph[v][i]
                if e[1] > 0 and self.level[e[0]] < 0:
                    self.level[e[0]] = self.level[v] + 1
                    que.append(e[0])
    
    def dfs(self, v, t, f):
        if v == t:
            return f
        for i in range(self.iter[v], len(self.graph[v])):
            self.iter[v] = i
            e = self.graph[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.graph[e[0]][e[2]][1] += d
                    return d
        return 0
    
    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            if self.level[t] < 0:
                return flow
            self.iter = [0]*self.vertice

            f = self.dfs(s, t, self.inf)
            while f:
                flow += f
                f = self.dfs(s, t, self.inf)
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 = Dinic(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*m+j+1, 1, reverse=False)
                    for x, y in direction:
                        ni, nj = x + i, y + j
                        if 0 <= ni < n and 0 <= nj < m and s[ni][nj] == 0:
                            p, q = min(i*m+j+1, ni*m+nj+1), max(i*m+j+1, ni*m+nj+1)
                            flow.add_edge(p, q, 1, reverse=False)
                else:
                    flow.add_edge(i*m+j+1, end, 1, reverse=False)
    

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

    ans = [["#" if s[i][j] else "." for j in range(n)] for i in range(n)]
    try:
        flow_list = []
        for i, g in enumerate(flow.graph):
            for node in g:
                fr, to = i, node[0]
                if fr > to:
                    continue
                if fr == start or to == end:
                    continue
                cap = node[1]
                if cap == 0:
                    flow_list.append((fr-1, to-1))
                
        for k, v in flow_list:
            if v-k == m:
                ans[k//m][k%m] = "v"
                ans[v//m][v%m] = "^"
            else:
                ans[k//m][k%m] = ">"
                ans[v//m][v%m] = "<"

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

    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
sys.setrecursionlimit(100000)
input = sys.stdin.readline


class Dinic:
    def __init__(self, v):
        self.vertice = v
        self.inf = int(1e9)
        self.graph = [[] for i in range(v)]
        self.level = [0]*v
        self.iter = [0]*v
    
    def add_edge(self, fr, to, cap, reverse=True):
        self.graph[fr].append([to, cap, len(self.graph[to])])
        cap2 = cap if reverse else 0
        self.graph[to].append([fr, cap2, len(self.graph[fr])-1])
    
    def bfs(self, s):
        self.level = [-1]*self.vertice
        que = deque([])
        self.level[s] = 0
        que.append(s)

        while que:
            v = que.popleft()
            for i in range(len(self.graph[v])):
                e = self.graph[v][i]
                if e[1] > 0 and self.level[e[0]] < 0:
                    self.level[e[0]] = self.level[v] + 1
                    que.append(e[0])
    
    def dfs(self, v, t, f):
        if v == t:
            return f
        for i in range(self.iter[v], len(self.graph[v])):
            self.iter[v] = i
            e = self.graph[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.graph[e[0]][e[2]][1] += d
                    return d
        return 0
    
    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            if self.level[t] < 0:
                return flow
            self.iter = [0]*self.vertice

            f = self.dfs(s, t, self.inf)
            while f:
                flow += f
                f = self.dfs(s, t, self.inf)
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 = Dinic(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*m+j+1, 1, reverse=False)
                    for x, y in direction:
                        ni, nj = x + i, y + j
                        if 0 <= ni < n and 0 <= nj < m and s[ni][nj] == 0:
                            p, q = min(i*m+j+1, ni*m+nj+1), max(i*m+j+1, ni*m+nj+1)
                            flow.add_edge(p, q, 1, reverse=False)
                else:
                    flow.add_edge(i*m+j+1, end, 1, reverse=False)
    

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

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

    flow_list = []
    for i, g in enumerate(flow.graph):
        for node in g:
            fr, to = i, node[0]
            if fr == start or fr == end or to == start or to == end:
                continue
            if fr > to:
                continue
            cap = node[1]
            if cap == 0:
                flow_list.append((fr-1, to-1))
            
    for k, v in flow_list:
        if m > 1 and v-k == 1:
            ans[k//m][k%m] = ">"
            ans[v//m][v%m] = "<"
        else:
            ans[k//m][k%m] = "v"
            ans[v//m][v%m] = "^"


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


    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
input = sys.stdin.readline


class Dinic:
    def __init__(self, v):
        self.vertice = v
        self.inf = int(1e9)
        self.graph = [[] for i in range(v)]
        self.level = [0]*v
        self.iter = [0]*v
    
    def add_edge(self, fr, to, cap):
        self.graph[fr].append([to, cap, len(self.graph[to])])
        self.graph[to].append([fr, cap, len(self.graph[fr])-1])
    
    def bfs(self, s):
        self.level = [-1]*self.vertice
        que = deque([])
        self.level[0] = s
        que.append(s)

        while que:
            v = que.popleft()
            for i in range(len(self.graph[v])):
                e = self.graph[v][i]
                if e[1] > 0 and self.level[e[0]] < 0:
                    self.level[e[0]] = self.level[v] + 1
                    que.append(e[0])
    
    def dfs(self, v, t, f):
        if v == t:
            return f
        for i in range(self.iter[v], len(self.graph[v])):
            self.iter[v] = i
            e = self.graph[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.graph[e[0]][e[2]][1] += d
                    return d
        return 0
    
    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            if self.level[t] < 0:
                return flow
            self.iter = [0]*self.vertice

            f = 1
            while f:
                f = self.dfs(s, t, self.inf)
                if f == 0:
                    break
                flow += f


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 = Dinic(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*m+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*m+j+1, ni*m+nj+1, 1)
                else:
                    flow.add_edge(i*m+j+1, end, 1)
    

    res = flow.max_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 i, g in enumerate(flow.graph):
        for node in g:
            fr, to = i, node[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//m][k%m] = ">"
            ans[v//m][v%m] = "<"
        else:
            ans[k//m][k%m] = "v"
            ans[v//m][v%m] = "^"


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


    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
input = sys.stdin.readline


class Dinic:
    def __init__(self, v):
        self.vertice = v
        self.inf = int(1e9)
        self.graph = [[] for i in range(v)]
        self.level = [0]*v
        self.iter = [0]*v
    
    def add_edge(self, fr, to, cap):
        self.graph[fr].append([to, cap, len(self.graph[to])])
        self.graph[to].append([fr, cap, len(self.graph[fr])-1])
    
    def bfs(self, s):
        self.level = [-1]*self.vertice
        que = deque([])
        self.level[0] = s
        que.append(s)

        while que:
            v = que.popleft()
            for i in range(len(self.graph[v])):
                e = self.graph[v][i]
                if e[1] > 0 and self.level[e[0]] < 0:
                    self.level[e[0]] = self.level[v] + 1
                    que.append(e[0])
    
    def dfs(self, v, t, f):
        if v == t:
            return f
        for i in range(self.iter[v], len(self.graph[v])):
            self.iter[v] = i
            e = self.graph[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.graph[e[0]][e[2]][1] += d
                    return d
        return 0
    
    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            if self.level[t] < 0:
                return flow
            self.iter = [0]*self.vertice

            f = 1
            while f:
                f = self.dfs(s, t, self.inf)
                if f == 0:
                    break
                flow += f


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 = Dinic(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.max_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 i, g in enumerate(flow.graph):
        for node in g:
            fr, to = i, node[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

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

  if N == M == 1:
    print(0)
    print(S[0][0])
    exit()

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

  G=nx.Graph()
  dx,dy=(1,0),(0,1)
  E = []
  n1,n2 = [],[]
  for i in range(N):
    for j in range(M):
      if S[i][j]=='#':continue
      if (i+j)%2:
        n1.append(index(i,j))
      else:
        n2.append(index(i,j))
      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:
          E.append((v2,v1))
        else:
          E.append((v1,v2))
     
  G.add_nodes_from(n1, bipartite=0)
  G.add_nodes_from(n2, bipartite=1)
  G.add_edges_from(E)
  match = nx.bipartite.maximum_matching(G)
  match = {v:match[v] for v in match.keys() if v < match[v]}
 
  for v in match.keys():
    i1,j1 = divmod(v,M)
    i2,j2 = divmod(match[v],M)
    if i1 > i2 or j1 > j2:
      (i1,j1),(i2,j2) = (i2,j2),(i1,j1)
    if i1 < i2:
      S[i1][j1] = 'v'
      S[i2][j2] = '^'
    else:
      S[i1][j1] = '>'
      S[i2][j2] = '<'

  print(len(match))
  for i in range(N):
    print(''.join(S[i]))
    
if __name__ == "__main__":
  main()

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
input = sys.stdin.readline


class Dinic:
    def __init__(self, v):
        self.vertice = v
        self.inf = int(1e9)
        self.graph = [[] for i in range(v)]
        self.level = [[] for i in range(v)]
        self.iter = [[] for i in range(v)]
    
    def add_edge(self, fr, to, cap):
        self.graph[fr].append([to, cap, len(self.graph[to])])
        self.graph[to].append([fr, cap, len(self.graph[fr])])
    
    def bfs(self, s):
        self.level = [-1]*self.vertice
        que = deque([])
        self.level[0] = s
        que.append(s)

        while que:
            v = que.pop()
            for i in range(len(self.graph[v])):
                if self.graph[v][i][1] > 0 and self.level[self.graph[v][i][0]] < 0:
                    self.level[self.graph[v][i][0]] = self.level[v] + 1
                    que.append(self.graph[v][i][0])
    
    def dfs(self, v, t, f):
        if v == t:
            return f
        for i in range(len(self.graph[v])):
            if self.graph[v][i][1] > 0 and self.level[v] < self.level[self.graph[v][i][0]]:
                d = self.dfs(self.graph[v][i][0], t, min(f, self.graph[v][i][1]))
                if d > 0:
                    self.graph[v][i][1] -= d
                    self.graph[self.graph[v][i][0]][self.graph[v][i][2]][1] += d
                    return d
            self.iter[v] += 1
        return 0
    
    def max_flow(self, s, t):
        flow = 0
        while True:
            self.bfs(s)
            if self.level[t] < 0:
                return flow
            self.iter = [0]*self.vertice

            f = 1
            while f:
                f = self.dfs(s, t, self.inf)
                if f == 0:
                    break
                flow += f


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 = Dinic(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.max_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 i, g in enumerate(flow.graph):
        for node in g:
            fr, to = i, node[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

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

  if N == M == 1:
    print(0)
    print(S[0][0])
    exit()

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

  G=nx.DiGraph()
  G.add_node('source')
  G.add_node('sink')
  dx,dy=(1,0),(0,1)
  E = []
  for i in range(N):
    for j in range(M):
      if S[i][j]=='#':continue
      if (i+j) %2:
        E.append((index(i,j),'sink'))
      else:
        E.append(('source',index(i,j))
      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:
          E.append((v2,v1))
        else:
          E.append((v1,v2))
     
  G.add_edges_from(E,capacity=1)
  flow_value, flow_dict = nx.maximum_flow(G, "source", "sink")

  for v1 in flow_dict.keys():
    if v1 in ('sink','source'):continue
    for v2 in flow_dict[v1].keys():
      if v2 in ('sink','source'):continue
      if flow_dict[v1][v2]:
        i1,j1 = divmod(v1,M)
        i2,j2 = divmod(v2,M)
        if i1 > i2 or j1 > j2:
          (i1,j1),(i2,j2) = (i2,j2),(i1,j1)
        if i1 < i2:
          S[i1][j1] = 'v'
          S[i2][j2] = '^'
        else:
          S[i1][j1] = '>'
          S[i2][j2] = '<'

  print(flow_value)
  for i in range(N):
    print(''.join(S[i]))
    
if __name__ == "__main__":
  main()

Submission status: Runtime Error

Solution code:
import networkx as nx

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

  if N == M == 1:
    print(0)
    print(S[0][0])
    exit()

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

  G=nx.DiGraph()
  G.add_node('source')
  G.add_node('sink')
  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")
  assert False

  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:
          S[i1][j1] = 'v'
          S[i2][j2] = '^'
        else:
          S[i1][j1] = '>'
          S[i2][j2] = '<'

  print(flow_value)
  for i in range(N):
    print(''.join(S[i]))
    
if __name__ == "__main__":
  main()

Submission status: Runtime Error

Solution code:
import networkx as nx

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

  if N == M == 1:
    print(0)
    print(S[0][0])
    exit()

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

  G=nx.DiGraph()
  G.add_node('source')
  G.add_node('sink')
  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)
         
  print(0/0)
  flow_value, flow_dict = nx.maximum_flow(G, "source", "sink")

  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:
          S[i1][j1] = 'v'
          S[i2][j2] = '^'
        else:
          S[i1][j1] = '>'
          S[i2][j2] = '<'

  print(flow_value)
  for i in range(N):
    print(''.join(S[i]))
    
if __name__ == "__main__":
  main()