There is a rectangular grid of size $n \times m$. Each cell of the grid is colored black ('0') or white ('1'). The color of the cell $(i, j)$ is $c_{i, j}$. You are also given a map of directions: for each cell, there is a direction $s_{i, j}$ which is one of the four characters 'U', 'R', 'D' and 'L'.

  If $s_{i, j}$ is 'U' then there is a transition from the cell $(i, j)$ to the cell $(i - 1, j)$;  if $s_{i, j}$ is 'R' then there is a transition from the cell $(i, j)$ to the cell $(i, j + 1)$;  if $s_{i, j}$ is 'D' then there is a transition from the cell $(i, j)$ to the cell $(i + 1, j)$;  if $s_{i, j}$ is 'L' then there is a transition from the cell $(i, j)$ to the cell $(i, j - 1)$. 

It is guaranteed that the top row doesn't contain characters 'U', the bottom row doesn't contain characters 'D', the leftmost column doesn't contain characters 'L' and the rightmost column doesn't contain characters 'R'.

You want to place some robots in this field (at most one robot in a cell). The following conditions should be satisfied.

  Firstly, each robot should move every time (i.e. it cannot skip the move). During one move each robot goes to the adjacent cell depending on the current direction.  Secondly, you have to place robots in such a way that there is no move before which two different robots occupy the same cell (it also means that you cannot place two robots in the same cell). I.e. if the grid is "RL" (one row, two columns, colors does not matter there) then you can place two robots in cells $(1, 1)$ and $(1, 2)$, but if the grid is "RLL" then you cannot place robots in cells $(1, 1)$ and $(1, 3)$ because during the first second both robots will occupy the cell $(1, 2)$. 

The robots make an infinite number of moves.

Your task is to place the maximum number of robots to satisfy all the conditions described above and among all such ways, you have to choose one where the number of black cells occupied by robots before all movements is the maximum possible. Note that you can place robots only before all movements.

You have to answer $t$ independent test cases.


-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 5 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains two integers $n$ and $m$ ($1 < nm \le 10^6$) — the number of rows and the number of columns correspondingly.

The next $n$ lines contain $m$ characters each, where the $j$-th character of the $i$-th line is $c_{i, j}$ ($c_{i, j}$ is either '0' if the cell $(i, j)$ is black or '1' if the cell $(i, j)$ is white).

The next $n$ lines also contain $m$ characters each, where the $j$-th character of the $i$-th line is $s_{i, j}$ ($s_{i, j}$ is 'U', 'R', 'D' or 'L' and describes the direction of the cell $(i, j)$).

It is guaranteed that the sum of the sizes of fields does not exceed $10^6$ ($\sum nm \le 10^6$).


-----Output-----

For each test case, print two integers — the maximum number of robots you can place to satisfy all the conditions described in the problem statement and the maximum number of black cells occupied by robots before all movements if the number of robots placed is maximized. Note that you can place robots only before all movements.


-----Example-----
Input
3
1 2
01
RL
3 3
001
101
110
RLL
DLD
ULL
3 3
000
000
000
RRD
RLD
ULL

Output
2 1
4 3
2 2

Source: codeforces | Difficulty: EASY


Solutions:
import sys
from collections import deque
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, m) = map(int, input().split())
	s = [input() for i in range(n)]
	grid = [input() for i in range(n)]
	robot_cnt = 0
	black_cnt = 0
	graph = [-1] * (n * m)
	rev_graph = [[] for i in range(n * m)]
	for i in range(n):
		for j in range(m):
			if grid[i][j] == 'U':
				graph[i * m + j] = (i - 1) * m + j
				rev_graph[(i - 1) * m + j].append(i * m + j)
			elif grid[i][j] == 'R':
				graph[i * m + j] = i * m + (j + 1)
				rev_graph[i * m + (j + 1)].append(i * m + j)
			elif grid[i][j] == 'D':
				graph[i * m + j] = (i + 1) * m + j
				rev_graph[(i + 1) * m + j].append(i * m + j)
			elif grid[i][j] == 'L':
				graph[i * m + j] = i * m + (j - 1)
				rev_graph[i * m + (j - 1)].append(i * m + j)
	is_start = [True] * (n * m)
	for i in graph:
		is_start[i] = False
	is_cycle = [False] * (n * m)
	period = [0] * (n * m)
	for i in range(n * m):
		if not is_start[i]:
			continue
		st = i
		period[i] = 1
		while True:
			nxt_i = graph[i]
			if period[nxt_i] < 0:
				tmp = period[nxt_i]
				break
			if period[nxt_i] > 0:
				tmp = -(period[i] - period[nxt_i] + 1)
				is_cycle[nxt_i] = True
				break
			period[graph[i]] = period[i] + 1
			i = graph[i]
		i = st
		period[i] = tmp
		while True:
			nxt_i = graph[i]
			if period[nxt_i] < 0:
				break
			period[graph[i]] = tmp
			i = graph[i]
	for i in range(n * m):
		if period[i] == 0:
			robot_cnt += 1
			if s[i // m][i % m] == '0':
				black_cnt += 1
	for i in range(n * m):
		if not is_cycle[i]:
			continue
		MOD = -period[i]
		period[i] = 0
		is_black = [False] * MOD
		if s[i // m][i % m] == '0':
			is_black[0] = True
		q = deque([i])
		while q:
			v = q.pop()
			for nxt_v in rev_graph[v]:
				if period[nxt_v] >= 0:
					continue
				period[nxt_v] = (period[v] + 1) % MOD
				if s[nxt_v // m][nxt_v % m] == '0':
					is_black[period[nxt_v]] = True
				q.append(nxt_v)
		robot_cnt += MOD
		black_cnt += sum(is_black)
	print(robot_cnt, black_cnt)


import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__

def go():
	(n, m) = map(int, input().split())
	c = ''.join((input() for _ in range(n)))
	s = ''.join((input() for _ in range(n)))
	nm = n * m
	done = [False] * nm
	groups = [None] * nm
	phase = [-1] * nm

	def step(pos, direct=None):
		if direct is None:
			direct = s[pos]
		if direct == 'U':
			return pos - m
		if direct == 'D':
			return pos + m
		if direct == 'L':
			return pos - 1
		if direct == 'R':
			return pos + 1
	cyc_len = {}
	for i in range(nm):
		if not done[i]:
			same = {}
			pos = 0
			cur = i
			group = -1
			pcur = None
			while cur not in same:
				if groups[cur] is not None:
					group = groups[cur]
					pcur = pos + phase[cur]
					break
				same[cur] = pos
				done[cur] = True
				cur = step(cur)
				pos += 1
			else:
				group = cur
				cyc_len[group] = len(same) - same[cur]
				pcur = pos
			for (ss, pos) in same.items():
				groups[ss] = group
				phase[ss] = (pcur - pos) % cyc_len[group]
	blacks = len(set(((pp, gg) for (cc, pp, gg) in zip(c, phase, groups) if cc == '0')))
	return f'{sum(cyc_len.values())} {blacks}'
t = int(input())
ans = []
for _ in range(t):
	ans.append(str(go()))
print('\n'.join(ans))


import io
import os
from collections import Counter, defaultdict, deque

def findCycle(source, getNbr):
	q = deque([source])
	parent = {source: None}
	while q:
		node = q.popleft()
		for nbr in getNbr(node):
			if nbr not in parent:
				q.append(nbr)
				parent[nbr] = node
			else:
				cycle = [node]
				while parent[node] != nbr:
					node = parent[node]
					cycle.append(node)
				cycle.append(nbr)
				return cycle

def markTime(cycle, getNbr):
	cycleLen = len(cycle)
	q = deque(cycle)
	dist = {x: i for (i, x) in enumerate(cycle)}
	while q:
		node = q.popleft()
		d = dist[node]
		for nbr in getNbr(node):
			if nbr not in dist:
				q.append(nbr)
				dist[nbr] = (d + 1) % cycleLen
	return dist

def solve(R, C, grid, directions):
	BLACK = 0
	WHITE = 1
	drdc = {'U': [-1, 0], 'R': [0, 1], 'D': [1, 0], 'L': [0, -1]}

	def getNbr(i):
		(r, c) = divmod(i, C)
		(dr, dc) = drdc[directions[r][c]]
		return [(r + dr) * C + (c + dc)]

	def getNbrT(i):
		(r, c) = divmod(i, C)
		ret = []
		for (dr, dc) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
			nr = r + dr
			nc = c + dc
			if 0 <= nr < R and 0 <= nc < C:
				if [-dr, -dc] == drdc[directions[nr][nc]]:
					ret.append(nr * C + nc)
		return ret
	ans1 = 0
	ans2 = 0
	seen = set()
	for i in range(R * C):
		if i not in seen:
			cycle = findCycle(i, getNbr)
			uniqueTimes = len(cycle)
			dist = markTime(cycle, getNbrT)
			uniqueBlackTimes = set()
			for (j, t) in dist.items():
				(r, c) = divmod(j, C)
				if grid[r][c] == BLACK:
					uniqueBlackTimes.add(t)
				seen.add(j)
			ans1 += uniqueTimes
			ans2 += len(uniqueBlackTimes)
			del cycle
			del dist
			del uniqueBlackTimes
	return str(ans1) + ' ' + str(ans2)
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(R, C) = [int(x) for x in input().split()]
	grid = [list(map(int, input().decode().rstrip())) for r in range(R)]
	directions = [list(input().decode().rstrip()) for r in range(R)]
	ans = solve(R, C, grid, directions)
	print(ans)


from sys import stdin, gettrace
if not gettrace():

	def input():
		return next(stdin)[:-1]

def main():

	def solve():
		(n, m) = map(int, input().split())
		colour = []
		for _ in range(n):
			colour.append(input())
		dir = []
		for _ in range(n):
			dir.append(input())
		lc = [[None] * m for _ in range(n)]
		next_trail = 0
		trails = []
		traills = []
		maxels = 0
		for ni in range(n):
			for nj in range(m):
				if not lc[ni][nj]:
					i = ni
					j = nj
					trail = []
					count = 1
					while not lc[i][j]:
						trail.append((i, j))
						lc[i][j] = (count, next_trail)
						count += 1
						if dir[i][j] == 'L':
							j -= 1
						elif dir[i][j] == 'R':
							j += 1
						elif dir[i][j] == 'U':
							i -= 1
						else:
							i += 1
					trpos = lc[i][j][0]
					found_trail = lc[i][j][1]
					if found_trail == next_trail:
						ls = count - trpos
						for (ix, (k, l)) in enumerate(trail[::-1]):
							lc[k][l] = (ix % ls, next_trail)
						traills.append(ls)
						trails.append(trail)
						maxels += ls
						next_trail += 1
					else:
						ls = traills[found_trail]
						for (ix, (k, l)) in enumerate(trail[::-1], 1):
							lc[k][l] = ((ix + trpos) % ls, found_trail)
						trails[found_trail] += trail
		blacks = 0
		for i in range(len(trails)):
			found = [False] * traills[i]
			for (k, l) in trails[i]:
				if colour[k][l] == '0' and (not found[lc[k][l][0]]):
					blacks += 1
					found[lc[k][l][0]] = True
		print(maxels, blacks)
	q = int(input())
	for _ in range(q):
		solve()
main()


import sys
from collections import deque

def bfs(source, getNbr):
	q = deque([source])
	dist = {source: 0}
	while q:
		node = q.popleft()
		d = dist[node]
		for nbr in getNbr(node):
			if nbr not in dist:
				q.append(nbr)
				dist[nbr] = d + 1
	return dist

def solve(R, C, grid, directions):
	BLACK = 0
	drdc = {'U': [-1, 0], 'R': [0, 1], 'D': [1, 0], 'L': [0, -1]}

	def getNbr(i):
		(r, c) = divmod(i, C)
		(dr, dc) = drdc[directions[r][c]]
		return [(r + dr) * C + (c + dc)]

	def getNbrT(i):
		(r, c) = divmod(i, C)
		ret = []
		for (dr, dc) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
			nr = r + dr
			nc = c + dc
			if 0 <= nr < R and 0 <= nc < C:
				if [-dr, -dc] == drdc[directions[nr][nc]]:
					ret.append(nr * C + nc)
		return ret
	ans1 = 0
	ans2 = 0
	seen = set()
	for i in range(R * C):
		if i not in seen:
			cycleIndices = {i: 0}
			cycle = [i]
			while True:
				(nbr,) = getNbr(cycle[-1])
				if nbr in cycleIndices:
					cycle = cycle[cycleIndices[nbr]:]
					break
				cycleIndices[nbr] = len(cycle)
				cycle.append(nbr)
			uniqueTimes = len(cycle)
			ans1 += uniqueTimes
			dist = bfs(cycle[-1], getNbrT)
			uniqueBlackTimes = set()
			for (j, time) in dist.items():
				(r, c) = divmod(j, C)
				if grid[r][c] == BLACK:
					uniqueBlackTimes.add(time % uniqueTimes)
				seen.add(j)
			ans2 += len(uniqueBlackTimes)
			del cycle
			del dist
			del uniqueBlackTimes
	return str(ans1) + ' ' + str(ans2)
input = sys.stdin.readline
T = int(input())
for t in range(T):
	(R, C) = [int(x) for x in input().split()]
	grid = [list(map(int, input().rstrip())) for r in range(R)]
	directions = [list(input().rstrip()) for r in range(R)]
	ans = solve(R, C, grid, directions)
	print(ans)


from sys import stdin, gettrace
if not gettrace():

	def input():
		return next(stdin)[:-1]

def main():

	def solve():
		(n, m) = map(int, input().split())
		colour = []
		for _ in range(n):
			colour.append(input())
		dir = []
		for _ in range(n):
			dir.append(input())
		eqgrid = [[None] * m for _ in range(n)]
		next_path = 0
		pathsizes = []
		eclass_has_black = []
		totls = 0
		for ni in range(n):
			for nj in range(m):
				if eqgrid[ni][nj]:
					continue
				i = ni
				j = nj
				path = []
				count = 1
				while not eqgrid[i][j]:
					path.append((i, j))
					eqgrid[i][j] = (count, next_path)
					count += 1
					if dir[i][j] == 'L':
						j -= 1
					elif dir[i][j] == 'R':
						j += 1
					elif dir[i][j] == 'U':
						i -= 1
					else:
						i += 1
				(ppos, found_path) = eqgrid[i][j]
				if found_path == next_path:
					ls = count - ppos
					eclass_has_black.append([False] * ls)
					for (ix, (k, l)) in enumerate(path[::-1]):
						eq = ix % ls
						eqgrid[k][l] = (eq, next_path)
						if colour[k][l] == '0':
							eclass_has_black[next_path][eq] = True
					pathsizes.append(ls)
					totls += ls
					next_path += 1
				else:
					ls = pathsizes[found_path]
					for (ix, (k, l)) in enumerate(path[::-1], 1):
						eq = (ix + ppos) % ls
						eqgrid[k][l] = (eq, found_path)
						if colour[k][l] == '0':
							eclass_has_black[found_path][eq] = True
		blacks = len([b for p in eclass_has_black for b in p if b])
		print(totls, blacks)
	q = int(input())
	for _ in range(q):
		solve()
main()


import sys
from collections import deque
import gc

def findCycle(source, getNbr):
	q = deque([source])
	parent = {source: None}
	while q:
		node = q.popleft()
		for nbr in getNbr(node):
			if nbr not in parent:
				q.append(nbr)
				parent[nbr] = node
			else:
				cycle = [node]
				while parent[node] != nbr:
					node = parent[node]
					cycle.append(node)
				cycle.append(nbr)
				return cycle[::-1]

def markTime(cycle, getNbr):
	cycleLen = len(cycle)
	q = deque(cycle)
	dist = {x: cycleLen - 1 - i for (i, x) in enumerate(cycle)}
	while q:
		node = q.popleft()
		d = dist[node]
		for nbr in getNbr(node):
			if nbr not in dist:
				q.append(nbr)
				dist[nbr] = (d + 1) % cycleLen
	return dist

def solve(R, C, grid, directions):
	BLACK = 0
	drdc = {'U': [-1, 0], 'R': [0, 1], 'D': [1, 0], 'L': [0, -1]}

	def getNbr(i):
		(r, c) = divmod(i, C)
		(dr, dc) = drdc[directions[r][c]]
		return [(r + dr) * C + (c + dc)]

	def getNbrT(i):
		(r, c) = divmod(i, C)
		ret = []
		for (dr, dc) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
			nr = r + dr
			nc = c + dc
			if 0 <= nr < R and 0 <= nc < C:
				if [-dr, -dc] == drdc[directions[nr][nc]]:
					ret.append(nr * C + nc)
		return ret
	ans1 = 0
	ans2 = 0
	seen = set()
	for i in range(R * C):
		if i not in seen:
			cycle = findCycle(i, getNbr)
			uniqueTimes = len(cycle)
			dist = markTime(cycle, getNbrT)
			uniqueBlackTimes = set()
			for (j, t) in list(dist.items()):
				(r, c) = divmod(j, C)
				if grid[r][c] == BLACK:
					uniqueBlackTimes.add(t)
				seen.add(j)
			ans1 += uniqueTimes
			ans2 += len(uniqueBlackTimes)
			del cycle
			del dist
			del uniqueBlackTimes
	return str(ans1) + ' ' + str(ans2)

def __starting_point():
	input = sys.stdin.readline
	T = int(input())
	for t in range(T):
		(R, C) = [int(x) for x in input().split()]
		grid = [list(map(int, input().rstrip())) for r in range(R)]
		directions = [list(input().rstrip()) for r in range(R)]
		ans = solve(R, C, grid, directions)
		print(ans)
__starting_point()


import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	for _ in range(II()):
		(h, w) = MI()
		cc = [list(map(int, list(SI()))) for _ in range(h)]
		ss = [SI() for _ in range(h)]
		aa = [[0] * w for _ in range(h)]
		mm = [[0] * w for _ in range(h)]
		cyc = [0]
		ci = 1
		dir = 'UDLR'
		dij = [(-1, 0), (1, 0), (0, -1), (0, 1)]
		for si in range(h):
			for sj in range(w):
				if aa[si][sj] != 0:
					continue
				(i, j) = (si, sj)
				d = -1
				stack = []
				while aa[i][j] == 0:
					aa[i][j] = d
					stack.append((i, j))
					d -= 1
					(di, dj) = dij[dir.index(ss[i][j])]
					(i, j) = (i + di, j + dj)
				if aa[i][j] > 0:
					a = aa[i][j]
					dist = cyc[a]
					m = (mm[i][j] + 1) % dist
					for (i, j) in stack[::-1]:
						aa[i][j] = a
						mm[i][j] = m
						m = (m + 1) % dist
				else:
					dist = aa[i][j] - d
					cyc.append(dist)
					m = 0
					for (i, j) in stack[::-1]:
						aa[i][j] = ci
						mm[i][j] = m
						m = (m + 1) % dist
					ci += 1
		one = [set() for _ in range(ci)]
		for i in range(h):
			for j in range(w):
				if cc[i][j] == 0:
					one[aa[i][j]].add(mm[i][j])
		ans1 = sum(cyc)
		ans2 = sum((min(ck, len(ok)) for (ck, ok) in zip(cyc, one)))
		print(ans1, ans2)
main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import deque

def dfs(alpha, id):
	stack = [alpha]
	cycle = None
	while stack:
		v = stack[-1]
		if not visited[v]:
			visited[v] = True
			u = graph[v]
			if 1:
				if not visited[u]:
					stack.append(u)
				elif visited[u] and ids[u] != -1:
					id = ids[u]
					cycleid = u
				else:
					cycle = (u, v)
		else:
			break
	if not cycle:
		result = stack
		for i in range(len(result)):
			ids[result[i]] = id
			cyclelength[result[i]] = cyclelength[cycleid]
			cycledistance[result[i]] = (cycledistance[cycleid] - (len(result) - i)) % cyclelength[result[i]]
	else:
		index = []
		result = stack
		for i in range(len(result)):
			ids[result[i]] = id
			if result[i] == cycle[0] or result[i] == cycle[1]:
				index += [i]
		for i in range(len(result)):
			if i < index[0]:
				cycledistance[result[i]] = (i - index[0]) % (index[1] - index[0] + 1)
			else:
				cycledistance[result[i]] = (i - index[0]) % (index[1] - index[0] + 1)
			cyclelength[result[i]] = index[1] - index[0] + 1
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	colors = [-1]
	for i in range(n):
		colors += [int(k) for k in input()]
	graph = [0] * (n * m + 1)
	for i in range(n):
		line = input()
		for j in range(m):
			if line[j] == 'R':
				graph[i * m + j + 1] = i * m + j + 2
			elif line[j] == 'L':
				graph[i * m + j + 1] = i * m + j
			elif line[j] == 'U':
				graph[i * m + j + 1] = (i - 1) * m + j + 1
			else:
				graph[i * m + j + 1] = (i + 1) * m + j + 1
	visited = [False] * len(graph)
	ids = [-1] * len(graph)
	cycledistance = [0] * len(graph)
	cyclelength = [0] * len(graph)
	id = 0
	oo = []
	for i in range(1, len(graph)):
		if not visited[i]:
			dfs(i, id)
			if ids[i] == id:
				id += 1
				oo += [[0] * cyclelength[i]]
	black = 0
	white = 0
	for i in range(1, len(graph)):
		if colors[i] == 0:
			if not oo[ids[i]][cycledistance[i]]:
				black += 1
				oo[ids[i]][cycledistance[i]] = 1
	for i in range(1, len(graph)):
		if colors[i] == 1:
			if not oo[ids[i]][cycledistance[i]]:
				white += 1
				oo[ids[i]][cycledistance[i]] = 1
	print(white + black, black)


import sys
from array import array

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def build_scc(V: int, adj: list) -> list:
	(state, low, order) = ([0] * V, [0] * V, [0] * V)
	(group_id, time) = (1, 1)
	groups = []
	for i in range(V):
		if order[i]:
			continue
		(stack, rec) = ([i], [i])
		while rec:
			v = rec[-1]
			if not order[v]:
				low[v] = order[v] = time
				(time, state[v]) = (time + 1, -1)
			elif low[v] > low[adj[v]]:
				low[v] = low[adj[v]]
			for edge_i in range(state[v], 0):
				dest = adj[v]
				if not order[dest]:
					state[v] = edge_i + 1
					stack.append(dest)
					rec.append(dest)
					break
				elif state[dest] <= 0 and low[v] > order[dest]:
					low[v] = order[dest]
			else:
				if low[v] == order[v]:
					g = []
					while state[v] <= 0:
						g.append(stack[-1])
						state[stack.pop()] = group_id
					group_id += 1
					if len(g) > 1:
						groups.append(g)
				rec.pop()
	return groups
t = int(input())
ans = [''] * t
for ti in range(t):
	(n, m) = map(int, input().split())
	N = n * m
	dir_dict = {'L': -1, 'R': 1, 'U': -m, 'D': m}
	(adj, rev) = ([-1] * N, [[] for _ in range(N)])
	color = array('b', [0]) * N
	for i in range(n):
		for (v, c) in enumerate(map(int, input().rstrip()), start=i * m):
			color[v] = c
	for i in range(n):
		for (v, c) in enumerate(input().rstrip(), start=i * m):
			adj[v] = v + dir_dict[c]
			rev[v + dir_dict[c]].append(v)
	sccs = build_scc(N, adj)
	(ans_sum, ans_black) = (0, 0)
	visited = array('b', [0]) * N
	for scc in sccs:
		size = len(scc)
		black = [0] * size
		stack = []
		v = scc[0]
		for i in range(size):
			visited[v] = 1
			stack.append((v, i))
			v = adj[v]
		while stack:
			(v, mod) = stack.pop()
			if color[v] == 0:
				black[mod] = 1
			for dest in rev[v]:
				if visited[dest]:
					continue
				visited[dest] = 1
				stack.append((dest, mod - 1 if mod > 0 else size - 1))
		ans_sum += size
		ans_black += sum(black)
	ans[ti] = f'{ans_sum} {ans_black}'
sys.stdout.buffer.write('\n'.join(ans).encode('utf-8'))


import sys
input = sys.stdin.readline

def search(i, j):
	L = []
	c = 0
	while CHECK[i][j] == 1 << 30:
		L.append((i, j))
		CHECK[i][j] = c
		if MAP2[i][j] == 'U':
			i -= 1
		elif MAP2[i][j] == 'D':
			i += 1
		elif MAP2[i][j] == 'R':
			j += 1
		else:
			j -= 1
		c += 1
	if (i, j) in L:
		x = CHECK[i][j]
		y = CHECK[L[-1][0]][L[-1][1]]
		loop = abs(x - y) + 1
		for (x, y) in L:
			CHECK[x][y] %= loop
			LOOP[x][y] = loop
	else:
		loop = LOOP[i][j]
		c = CHECK[i][j]
		for (x, y) in L[::-1]:
			c = (c - 1) % loop
			CHECK[x][y] = c
			LOOP[x][y] = loop

def search2(i, j):
	Q = [(i, j)]
	ANS = [0] * LOOP[i][j]
	while Q:
		(x, y) = Q.pop()
		if USE[x][y] == 1:
			continue
		USE[x][y] = 1
		if MAP[x][y] == '0':
			ANS[CHECK[x][y]] = 1
		if MAP2[x][y] == 'U':
			Q.append((x - 1, y))
		elif MAP2[x][y] == 'D':
			Q.append((x + 1, y))
		elif MAP2[x][y] == 'R':
			Q.append((x, y + 1))
		else:
			Q.append((x, y - 1))
		if 0 <= x + 1 < n and 0 <= y < m and (MAP2[x + 1][y] == 'U'):
			Q.append((x + 1, y))
		if 0 <= x - 1 < n and 0 <= y < m and (MAP2[x - 1][y] == 'D'):
			Q.append((x - 1, y))
		if 0 <= x < n and 0 <= y + 1 < m and (MAP2[x][y + 1] == 'L'):
			Q.append((x, y + 1))
		if 0 <= x < n and 0 <= y - 1 < m and (MAP2[x][y - 1] == 'R'):
			Q.append((x, y - 1))
	return (LOOP[i][j], sum(ANS))
t = int(input())
for tests in range(t):
	(n, m) = list(map(int, input().split()))
	MAP = [input().strip() for i in range(n)]
	MAP2 = [input().strip() for i in range(n)]
	CHECK = [[1 << 30] * m for i in range(n)]
	LOOP = [[1 << 30] * m for i in range(n)]
	for i in range(n):
		for j in range(m):
			if CHECK[i][j] == 1 << 30:
				search(i, j)
	USE = [[0] * m for i in range(n)]
	ANSM = 0
	ANSC = 0
	for i in range(n):
		for j in range(m):
			if USE[i][j] == 0:
				(x, y) = search2(i, j)
				ANSM += x
				ANSC += y
	print(ANSM, ANSC)


from collections import defaultdict
import sys
from itertools import chain
input = sys.stdin.readline

def solve(n, adj, rev):
	(visited, order) = ([0] * n, [])
	for i in range(n):
		if visited[i]:
			continue
		stack = [i]
		while stack:
			v = stack.pop()
			visited[v] = 1
			if visited[adj[v]] == 0:
				visited[adj[v]] = 1
				stack.extend((v, adj[v]))
			else:
				order.append(v)
	groups = [0] * n
	g = 1
	while order:
		stack = [order.pop()]
		groups[stack[0]] = g
		while stack:
			v = stack.pop()
			for dest in rev[v]:
				if groups[dest]:
					continue
				groups[dest] = g
				stack.append(dest)
		g += 1
		while order and groups[order[-1]]:
			order.pop()
	return groups
for _ in range(int(input())):
	(h, w) = map(int, input().split())
	V = h * w
	adj = [0] * V
	rev = [[] for _ in range(V)]
	colors = list(chain.from_iterable((map(lambda x: int(x) ^ 1, input().rstrip()) for _ in range(h))))
	dirs = list(chain.from_iterable((input().rstrip() for _ in range(h))))
	delta = {'R': 1, 'L': -1, 'D': w, 'U': -w}
	for (i, d) in enumerate(dirs):
		adj[i] = i + delta[d]
		rev[i + delta[d]].append(i)
	dd = defaultdict(list)
	for (i, g) in enumerate(solve(V, adj, rev)):
		dd[g].append(i)
	(ans_robot, ans_black) = (0, 0)
	group = [-1] * V
	for cycle in dd.values():
		size = len(cycle)
		if size == 1:
			continue
		black = [0] * size
		cur = cycle[0]
		for i in range(size):
			group[cur] = i
			black[i] = colors[cur]
			cur = adj[cur]
		for s in cycle:
			stack = [s]
			while stack:
				v = stack.pop()
				black[group[v]] |= colors[v]
				for dest in rev[v]:
					if group[dest] != -1:
						continue
					group[dest] = (group[v] - 1) % size
					stack.append(dest)
		ans_robot += size
		ans_black += sum(black)
	sys.stdout.write(str(ans_robot) + ' ' + str(ans_black) + '\n')