It is the hard version of the problem. The difference is that in this version, there are nodes with already chosen colors.

Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?

You have a perfect binary tree of $2^k - 1$ nodes — a binary tree where all vertices $i$ from $1$ to $2^{k - 1} - 1$ have exactly two children: vertices $2i$ and $2i + 1$. Vertices from $2^{k - 1}$ to $2^k - 1$ don't have any children. You want to color its vertices with the $6$ Rubik's cube colors (White, Green, Red, Blue, Orange and Yellow).

Let's call a coloring good when all edges connect nodes with colors that are neighboring sides in the Rubik's cube.

A picture of Rubik's cube and its 2D map.

More formally:

a white node can not be neighboring with white and yellow nodes;

a yellow node can not be neighboring with white and yellow nodes;

a green node can not be neighboring with green and blue nodes;

a blue node can not be neighboring with green and blue nodes;

a red node can not be neighboring with red and orange nodes;

an orange node can not be neighboring with red and orange nodes;

However, there are $n$ special nodes in the tree, colors of which are already chosen.

You want to calculate the number of the good colorings of the binary tree. Two colorings are considered different if at least one node is colored with a different color.

The answer may be too large, so output the answer modulo $10^9+7$.


-----Input-----

The first line contains the integers $k$ ($1 \le k \le 60$) — the number of levels in the perfect binary tree you need to color.

The second line contains the integer $n$ ($1 \le n \le \min(2^k - 1, 2000)$) — the number of nodes, colors of which are already chosen.

The next $n$ lines contains integer $v$ ($1 \le v \le 2^k - 1$) and string $s$ — the index of the node and the color of the node ($s$ is one of the white, yellow, green, blue, red and orange).

It is guaranteed that each node $v$ appears in the input at most once.


-----Output-----

Print one integer — the number of the different colorings modulo $10^9+7$.


-----Examples-----

Input
3
2
5 orange
2 white
Output
1024
Input
2
2
1 white
2 white
Output
0
Input
10
3
1 blue
4 red
5 orange
Output
328925088


-----Note-----

In the picture below, you can see one of the correct colorings of the first test example.

Source: codeforces | Difficulty: HARD
Tags: Implementation

Complete search

Tree algorithms

Dynamic programming

Mathematics


Solutions:
import sys
import getpass
import math, random
import functools, itertools, collections, heapq, bisect
from collections import Counter, defaultdict, deque
input = sys.stdin.readline
M9 = 10 ** 9 + 7
(yes, no) = ('YES', 'NO')
MAXINT = sys.maxsize
OFFLINE_TEST = getpass.getuser() == 'hkmac'

def log(*args):
	if OFFLINE_TEST:
		print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)

def solve(*args):
	if OFFLINE_TEST:
		log('----- solving ------')
		log(*args)
		log('----- ------- ------')
	return solve_(*args)

def read_matrix(rows):
	return [list(map(int, input().split())) for _ in range(rows)]

def read_strings(rows):
	return [list(input().split()) for _ in range(rows)]

def minus_one(arr):
	return [x - 1 for x in arr]

def minus_one_matrix(mrr):
	return [[x - 1 for x in row] for row in mrr]

def solve_(arr, k):
	unconstrainted = [1, 1]
	res = 1
	for _ in range(k - 1):
		new = 0
		new += 4 * res * 4 * res
		res = new % M9
		unconstrainted.append(res)
	unconstrainted = unconstrainted[::-1]
	log(unconstrainted)
	mapp = {}
	for (node, color, level) in arr[::-1]:
		node = -node
		log(node, node // 2)
		if node // 2 in mapp:
			if mapp[node // 2] == color or mapp[node // 2] == -color:
				return 0
		mapp[node] = color
	count = {}
	visited = set()
	while arr:
		(node, color, level) = heapq.heappop(arr)
		node = -node
		if node in visited:
			continue
		visited.add(node)
		left_child = node * 2
		right_child = node * 2 + 1
		res = [1, 1, 1]
		if left_child in count:
			(a0, a1, a2) = count[left_child]
		else:
			(a0, a1, a2) = [2 * unconstrainted[level], 2 * unconstrainted[level], 2 * unconstrainted[level]]
		if right_child in count:
			(b0, b1, b2) = count[right_child]
		else:
			(b0, b1, b2) = [2 * unconstrainted[level], 2 * unconstrainted[level], 2 * unconstrainted[level]]
		res[0] = a1 * b2 + a2 * b1 + a1 * b1 + a2 * b2
		res[1] = a2 * b0 + a0 * b2 + a2 * b2 + a0 * b0
		res[2] = a0 * b1 + a1 * b0 + a0 * b0 + a1 * b1
		if level == k:
			if color == 0:
				res = [2, 2, 2]
			else:
				res = [0, 0, 0]
				res[abs(color) - 1] = 1
		elif color != 0:
			col = abs(color) - 1
			r2 = res[col]
			res = [0, 0, 0]
			res[col] = r2
		else:
			res[0] *= 2
			res[1] *= 2
			res[2] *= 2
		res = [res[0] % M9, res[1] % M9, res[2] % M9]
		count[node] = res
		log(node, color, res)
		parent = node // 2
		heapq.heappush(arr, (-parent, 0, level - 1))
		if parent == 0:
			break
	return sum(count[1]) % M9
for case_num in [0]:
	k = int(input())
	mapp = {'white': 1, 'yellow': -1, 'green': 2, 'blue': -2, 'red': 3, 'orange': -3}
	r = int(input())
	arr = read_strings(r)
	arr = [(-int(x[0]), -abs(mapp[x[1]]), -2 + len(bin(int(x[0])))) for x in arr]
	arr.sort()
	res = solve(arr, k)
	print(res)


import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq

def input():
	return sys.stdin.readline()[:-1]
INF = 10 ** 10
MOD = 1000000007
K = int(input())
N = int(input())
Info = [list() for _ in range(K)]
color_dic = {'white': 0, 'green': 1, 'red': 2, 'yellow': 3, 'blue': 4, 'orange': 5}
for _ in range(N):
	(v, col) = input().split()
	d = 0
	v1 = int(v)
	while True:
		if v1 <= 2 ** d:
			break
		v1 -= 2 ** d
		d += 1
	Info[d].append((int(v), color_dic[col]))
for d in range(K):
	Info[d].sort()
dp = [[0] * 6 for _ in range(K)]
dp_sp = [collections.defaultdict(lambda : [0] * 6) for _ in range(K)]
for c in range(6):
	dp[K - 1][c] = 1
for (v, c) in Info[K - 1]:
	T = [0] * 6
	T[c] = 1
	dp_sp[K - 1][v] = T
for k in reversed(range(K - 1)):
	for c in range(6):
		for c1_1 in range(6):
			for c1_2 in range(6):
				if (c1_1 - c) % 3 and (c1_2 - c) % 3:
					dp[k][c] = (dp[k][c] + dp[k + 1][c1_1] * dp[k + 1][c1_2]) % MOD
	for (v1, t1) in dp_sp[k + 1].items():
		if v1 % 2 == 0 and v1 + 1 in dp_sp[k + 1]:
			v2 = v1 + 1
			t2 = dp_sp[k + 1][v2]
			T = [0] * 6
			for c in range(6):
				for c1_1 in range(6):
					for c1_2 in range(6):
						if (c1_1 - c) % 3 and (c1_2 - c) % 3:
							T[c] = (T[c] + t1[c1_1] * t2[c1_2]) % MOD
			dp_sp[k][v1 // 2] = T
			continue
		if v1 % 2 == 1 and v1 - 1 in dp_sp[k + 1]:
			continue
		T = [0] * 6
		for c in range(6):
			for c1_1 in range(6):
				for c1_2 in range(6):
					if (c1_1 - c) % 3 and (c1_2 - c) % 3:
						T[c] = (T[c] + t1[c1_1] * dp[k + 1][c1_2]) % MOD
		dp_sp[k][v1 // 2] = T
	for (v, c) in Info[k]:
		if v not in dp_sp[k]:
			dp_sp[k][v] = list(dp[k])
		for c1 in range(6):
			if c1 != c:
				dp_sp[k][v][c1] = 0
if N == 0:
	ans = sum(dp[0]) % MOD
else:
	ans = sum(dp_sp[0][1]) % MOD
print(ans)


k = int(input())
n = int(input())
l = [1]
m = 10 ** 9 + 7
for i in range(k - 1):
	l.append(16 * l[-1] ** 2 % m)
counts = {}
ind = {'white': 0, 'green': 1, 'red': 2, 'yellow': 3, 'blue': 4, 'orange': 5}
given = {}
for i in range(n):
	(v, c) = input().split()
	v = int(v)
	c = ind[c]
	given[v] = c

def count(k, i, counts, color=None):
	if i in counts:
		return None
	m = 10 ** 9 + 7
	if 2 * i not in counts and 2 * i + 1 not in counts:
		layer = len(bin(i)) - 2
		if color is None:
			counts[i] = [l[k - layer]] * 6
		else:
			counts[i] = [0] * 6
			counts[i][color] = l[k - layer]
	elif 2 * i in counts and 2 * i + 1 in counts:
		left = counts[2 * i]
		right = counts[2 * i + 1]
		new = [0] * 6
		for _ in range(6):
			totleft = sum(left) - left[_] - left[(_ + 3) % 6]
			totright = sum(right) - right[_] - right[(_ + 3) % 6]
			if color is None or _ == color:
				new[_] = totleft * totright % m
		counts[i] = new
	else:
		layer = len(bin(i)) - 2
		if 2 * i in counts:
			left = counts[2 * i]
			right = [l[k - layer - 1]] * 6
		else:
			left = counts[2 * i + 1]
			right = [l[k - layer - 1]] * 6
		new = [0] * 6
		for _ in range(6):
			totleft = sum(left) - left[_] - left[(_ + 3) % 6]
			totright = sum(right) - right[_] - right[(_ + 3) % 6]
			if color is None or _ == color:
				new[_] = totleft * totright % m
		counts[i] = new
bits = k
while bits > 0:
	for guy in list(counts.keys()):
		if len(bin(guy)) == bits + 3:
			color = given[guy // 2] if guy // 2 in given else None
			count(k, guy // 2, counts, color)
	for guy in given:
		if len(bin(guy)) == bits + 2:
			count(k, guy, counts, given[guy])
	bits -= 1
print(sum(counts[1]) % m)


import sys
from sys import stdin
cdic = {}
cdic['white'] = 0
cdic['yellow'] = 0
cdic['green'] = 1
cdic['blue'] = 1
cdic['red'] = 2
cdic['orange'] = 2
mod = 10 ** 9 + 7
k = int(stdin.readline())
n = int(stdin.readline())
dp = {}
dplis = []
vtos = {}
for i in range(n):
	(v, s) = stdin.readline()[:-1].split()
	v = int(v)
	vtos[v] = s
	while v != 0:
		if v not in dp:
			dp[v] = [0, 0, 0]
			dplis.append(v)
		v //= 2
dplis.sort()
dplis.reverse()

def getans(v, c):
	if v in dp:
		return dp[v][c]
	else:
		height = v.bit_length()
		remh = k - height + 1
		chnum = 2 ** remh - 1
		return pow(2, chnum - 1, mod)
for v in dplis:
	if 2 ** (k - 1) <= v:
		ncolor = cdic[vtos[v]]
		dp[v][ncolor] = 1
	else:
		for x in range(3):
			for y in range(3):
				for z in range(3):
					if x != y and x != z:
						dp[v][x] += getans(2 * v, y) * getans(2 * v + 1, z)
						dp[v][x] %= mod
		if v in vtos:
			ncolor = cdic[vtos[v]]
			for x in range(3):
				if x != ncolor:
					dp[v][x] = 0
ans = pow(2, 2 ** k - 1 - n, mod) * sum(dp[1])
print(ans % mod)


import sys
import io, os
input = sys.stdin.readline
from collections import defaultdict
k = int(input())
n = int(input())
toid = {'white': 0, 'yellow': 1, 'green': 2, 'blue': 3, 'red': 4, 'orange': 5}
edge = [[2, 3, 4, 5], [2, 3, 4, 5], [0, 1, 4, 5], [0, 1, 4, 5], [0, 1, 2, 3], [0, 1, 2, 3]]
mod = 10 ** 9 + 7
predefine = {}
V = []
for i in range(n):
	(v, s) = map(str, input().split())
	v = int(v)
	v -= 1
	s = toid[s]
	V.append(v)
	predefine[v] = s
X = set()
for v in V:
	X.add(v)
	while v:
		v = (v - 1) // 2
		X.add(v)
X = list(X)
X.sort(reverse=True)
S = set(X)
dp = defaultdict(lambda : [0] * 6)
for v in X:
	if v in predefine:
		c = predefine[v]
		dp[v] = [0] * 6
		(nx1, nx2) = (2 * v + 1, 2 * v + 2)
		if nx1 in S and nx2 in S:
			(s1, s2) = (0, 0)
			for j in edge[c]:
				s1 += dp[nx1][j]
				s2 += dp[nx2][j]
			dp[v][c] += s1 * s2 % mod
		elif nx1 in S:
			for j in edge[c]:
				dp[v][c] += dp[nx1][j] % mod
		elif nx2 in S:
			for j in edge[c]:
				dp[v][c] += dp[nx2][j] % mod
		else:
			dp[v][c] = 1
	else:
		for c in range(6):
			(nx1, nx2) = (2 * v + 1, 2 * v + 2)
			if nx1 in S and nx2 in S:
				(s1, s2) = (0, 0)
				for j in edge[c]:
					s1 += dp[nx1][j]
					s2 += dp[nx2][j]
				dp[v][c] += s1 * s2 % mod
			elif nx1 in S:
				for j in edge[c]:
					dp[v][c] += dp[nx1][j] % mod
			elif nx2 in S:
				for j in edge[c]:
					dp[v][c] += dp[nx2][j] % mod
			else:
				dp[v][c] = 1
cnt = pow(2, k) - 1 - len(S)
ans = sum(dp[0]) * pow(4, cnt, mod)
ans %= mod
print(ans)


import sys
input = sys.stdin.buffer.readline

def inp():
	return int(input())

def input_gen_list():
	return input()[:-1].split()

def input_list():
	return list(map(int, input().split()))

def input_string():
	s = input()
	return list(s[:len(s) - 1])

def input_int_gen():
	return map(int, input().split())
from collections import defaultdict
MOD = 10 ** 9 + 7
tests = 1
color = {'white': 1, 'yellow': 6, 'green': 2, 'blue': 5, 'red': 3, 'orange': 4}
counts = defaultdict(lambda : None)
mands = dict()
marks = set()
marks_ls = []

def powerm(a, b):
	prodi = 1
	base = a
	while b:
		if b % 2 == 1:
			prodi = prodi * base % MOD
		base = base * base % MOD
		b = b >> 1
	return prodi

def under(node, k):
	num_nodes = 2 ** (k - node.bit_length() + 1) - 2
	return powerm(4, num_nodes)

def mark_up(node):
	while node:
		marks.add(node)
		marks_ls.append(node)
		node = node // 2

def par_val(node1, node2):
	if node1 == node2 == None:
		return [1 for _ in range(7)]
	if node1 == None or node2 == None:
		node = node1 if node2 == None else node2
		ret = [0 for _ in range(7)]
		for x in range(1, 7):
			for y in range(1, 7):
				if x == y or x + y == 7:
					continue
				ret[x] = (ret[x] + node[y] % MOD) % MOD
		return ret
	ret = [0 for _ in range(7)]
	for x in range(1, 7):
		for y in range(1, 7):
			if x == y or x + y == 7:
				continue
			for z in range(1, 7):
				if x == z or x + z == 7:
					continue
				ret[x] = (ret[x] + node1[y] * node2[z] % MOD) % MOD
	return ret
for _ in range(tests):
	k = inp()
	n = inp()
	for _ in range(n):
		l = input_gen_list()
		(v, c) = (int(l[0]), color[l[1].decode()])
		mands[v] = c
		mark_up(v)
	marks_ls.sort(reverse=True)
	for node in marks_ls:
		(child1, child2) = (counts[node * 2], counts[node * 2 + 1])
		cur = par_val(child1, child2)
		if node in mands:
			counts[node] = [0 if i != mands[node] else x for (i, x) in enumerate(cur)]
		else:
			counts[node] = cur
	print(sum(counts[1]) * powerm(4, 2 ** k - 1 - len(marks)) % MOD)


import sys
MOD = int(1000000000.0 + 7)
colors_matrix = [[2, 4, 3, 5], [2, 4, 3, 5], [0, 1, 4, 5], [0, 1, 4, 5], [0, 1, 2, 3], [0, 1, 2, 3]]

def rec(tree, vertex, level):
	global dp
	if vertex not in tree:
		return [dp[level]] * 6
	vertex_color_restriction = tree[vertex]
	if level == 0:
		if vertex_color_restriction >= 0:
			res = [0] * 6
			res[vertex_color_restriction] = 1
			return res
		else:
			return [1] * 6
	left = rec(tree, vertex * 2, level - 1)
	right = rec(tree, vertex * 2 + 1, level - 1)
	res = [0] * 6
	for vertex_color in range(6):
		if vertex_color_restriction >= 0 and vertex_color_restriction != vertex_color:
			continue
		left_options = 0
		for color_left in colors_matrix[vertex_color]:
			left_options += left[color_left]
		right_options = 0
		for color_right in colors_matrix[vertex_color]:
			right_options += right[color_right]
		res[vertex_color] = left_options * right_options % MOD
	return res

def solve():
	global dp
	inp = sys.stdin.readline
	k = int(inp())
	n = int(inp())
	dp = [0] * k
	dp[0] = 1
	for i in range(1, k):
		dp[i] = dp[i - 1] * 4 * dp[i - 1] * 4 % MOD
	tree = {}
	color_to_id = {'white': 0, 'yellow': 1, 'green': 2, 'blue': 3, 'red': 4, 'orange': 5}
	for i in range(n):
		(v, s) = inp().split()
		v = int(v)
		tree[v] = color_to_id[s]
		v //= 2
		while v > 0:
			if v not in tree:
				tree[v] = -1
			v //= 2
	print(sum(rec(tree, 1, k - 1)) % MOD)

def main():
	solve()
main()


import sys
from collections import defaultdict as dd
input = sys.stdin.readline
mod = 10 ** 9 + 7
k = int(input())
n = int(input())
m = pow(2, k) - 1
d = {'white': 0, 'blue': 1, 'red': 2, 'orange': 3, 'green': 4, 'yellow': 5}
qs = []
for _ in range(n):
	(x, c) = input().split()
	x = int(x)
	qs.append((x, d[c]))
table = dd(lambda : -1)
for (x, c) in qs:
	table[x] = c
import heapq
hpush = heapq.heappush
hpop = heapq.heappop
h = []
vis = set()
dp = dd(lambda : [1] * 6)
for (x, c) in qs:
	hpush(h, -x)
	dp[x] = [0] * 6
	dp[x][c] = 1
while len(h):
	x = -hpop(h)
	if x in vis:
		continue
	vis.add(x)
	p = x // 2
	if p:
		hpush(h, -p)
	ndp = [0] * 6
	for i in range(6):
		for j in range(6):
			if i == j or i + j == 5:
				continue
			ndp[j] += dp[x][i] * dp[p][j] % mod
	dp[p] = ndp
res = sum(dp[1]) % mod * pow(4, m - len(vis), mod) % mod
print(res)


from collections import defaultdict
import sys
readline = sys.stdin.readline
K = int(readline())
N = int(readline())
color = ['white', 'green', 'red', 'yellow', 'blue', 'orange']
num = {color[i]: i for i in range(6)}
dp = defaultdict(lambda : defaultdict(int))
dct = {}
lst = []
for _ in range(N):
	(v, c) = readline().split()
	v = int(v)
	dct[v] = num[c]
	while v:
		lst.append(v)
		v //= 2
lst = list(set(lst))
lst.sort(reverse=True)
mod = 10 ** 9 + 7
for i in lst:
	if not i * 2 in dp and (not i * 2 + 1 in dp):
		if i in dct:
			dp[i][dct[i]] = 1
		else:
			for j in range(6):
				dp[i][j] = 1
	elif (i * 2 in dp) + (i * 2 + 1 in dp) == 1:
		(a, b) = (i * 2, i * 2 + 1)
		if not a in dp:
			(a, b) = (b, a)
		dp[i][0] = (dp[a][1] + dp[a][2] + dp[a][4] + dp[a][5]) % mod
		dp[i][1] = (dp[a][0] + dp[a][2] + dp[a][3] + dp[a][5]) % mod
		dp[i][2] = (dp[a][0] + dp[a][1] + dp[a][3] + dp[a][4]) % mod
		dp[i][3] = dp[i][0]
		dp[i][4] = dp[i][1]
		dp[i][5] = dp[i][2]
		if i in dct:
			for j in range(6):
				if j != dct[i]:
					dp[i][j] = 0
	else:
		dp[i][0] = (dp[i * 2][1] + dp[i * 2][2] + dp[i * 2][4] + dp[i * 2][5]) * (dp[i * 2 + 1][1] + dp[i * 2 + 1][2] + dp[i * 2 + 1][4] + dp[i * 2 + 1][5]) % mod
		dp[i][1] = (dp[i * 2][0] + dp[i * 2][2] + dp[i * 2][3] + dp[i * 2][5]) * (dp[i * 2 + 1][0] + dp[i * 2 + 1][2] + dp[i * 2 + 1][3] + dp[i * 2 + 1][5]) % mod
		dp[i][2] = (dp[i * 2][0] + dp[i * 2][1] + dp[i * 2][3] + dp[i * 2][4]) * (dp[i * 2 + 1][0] + dp[i * 2 + 1][1] + dp[i * 2 + 1][3] + dp[i * 2 + 1][4]) % mod
		dp[i][3] = dp[i][0]
		dp[i][4] = dp[i][1]
		dp[i][5] = dp[i][2]
		if i in dct:
			for j in range(6):
				if j != dct[i]:
					dp[i][j] = 0
ans = 0
for j in range(6):
	ans += dp[1][j]
	ans %= mod
ans *= pow(4, (1 << K) - 1 - len(dp), mod)
ans %= mod
print(ans)


MOD = 10 ** 9 + 7
color = {'white': 0, 'yellow': 5, 'green': 2, 'blue': 3, 'red': 4, 'orange': 1}
special = {}
marked = set()
k = int(input())
n = int(input())
dp = {}

def solve(i, j):
	if special.get(i, -1) != -1 and special[i] != j:
		return 0
	if dp[i][j] != -1:
		return dp[i][j]
	nodel = 2 * i
	noder = 2 * i + 1
	suml = 0
	sumr = 0
	for col in range(6):
		if col != 5 - j and col != j:
			if nodel in marked:
				suml += solve(nodel, col)
			else:
				suml = 1
			if noder in marked:
				sumr += solve(noder, col)
			else:
				sumr = 1
	dp[i][j] = suml * sumr % MOD
	return dp[i][j]
for _ in range(n):
	(v, s) = input().split(' ')
	v = int(v)
	special[v] = color[s]
	while v not in marked and v >= 1:
		marked.add(v)
		dp[v] = [-1] * 6
		v //= 2
res = 0
for col in range(6):
	res += solve(1, col)
unmarked_node = 2 ** k - 1 - len(marked)
ability_unmarked = pow(4, unmarked_node, MOD)
res %= MOD
res = res * ability_unmarked % MOD
print(res)


import io, os
M = 10 ** 9 + 7
colors = {'white': 0, 'yellow': 0, 'green': 1, 'blue': 1, 'red': 2, 'orange': 2}

def getnext(index, n, colored, dic, layer):
	if layer == n:
		if index not in dic:
			return [2, 2, 2]
		else:
			dic[index][colored[index]] += 1
			return dic[index]
	if index not in dic:
		rest = n - layer
		sub = pow(2, (1 << rest + 2) - 3, M)
		return [sub, sub, sub]
	left = getnext(2 * index, n, colored, dic, layer + 1)
	right = getnext(2 * index + 1, n, colored, dic, layer + 1)
	if index in colored:
		for i in range(3):
			if i != colored[index]:
				continue
			dic[index][i] = (sum(left) - left[i]) * (sum(right) - right[i])
			dic[index][i] = dic[index][i] % M
	else:
		for i in range(3):
			dic[index][i] = 2 * (sum(left) - left[i]) * (sum(right) - right[i])
			dic[index][i] = dic[index][i] % M
	return dic[index]

def main(t):
	M = 10 ** 9 + 7
	n = int(input())
	q = int(input())
	dic = {}
	colored = {}
	for _ in range(q):
		(i, color) = input().split()
		i = int(i)
		colored[i] = colors[color]
		while i > 0:
			if i not in dic:
				dic[i] = [0, 0, 0]
			i = i >> 1
	ans = getnext(1, n, colored, dic, 1)
	print(sum(ans) % M)
main(1)


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

def il():
	return list(map(int, input().split()))

def ii():
	return int(input())

def imi():
	return map(int, input().split())

def ist():
	return input()
k = ii()
n = ii()
p = 10 ** 9 + 7
tot = 2 ** k - 1

def powr(a, b):
	if b == 0:
		return 1
	if b == 1:
		return a
	x = powr(a, b // 2)
	if b % 2 == 0:
		return x * x % p
	else:
		return x * x * a % p

def solve(i, cl, dp, mk, vis, p):
	if i > tot:
		return 0
	if mk[i] == 0:
		return 0
	if mk[i] == -1:
		if dp[i, cl] == 0:
			return 0
	if vis[i, cl]:
		return dp[i, cl]
	c1 = 2 * i
	c2 = c1 + 1
	s = 0
	if mk[c1] != 0 and mk[c2] != 0:
		for j in range(1, 7):
			if j == cl or j + cl == 7:
				continue
			if vis[c1, j]:
				a = dp[c1, j]
			else:
				a = solve(c1, j, dp, mk, vis, p)
			for k in range(1, 7):
				if k == cl or k + cl == 7:
					continue
				if vis[c2, k]:
					b = dp[c2, k]
				else:
					b = solve(c2, k, dp, mk, vis, p)
				s = (s + a * b) % p
	elif mk[c1] != 0:
		for j in range(1, 7):
			if j == cl or j + cl == 7:
				continue
			if vis[c1, j]:
				a = dp[c1, j]
			else:
				a = solve(c1, j, dp, mk, vis, p)
			s = (s + a) % p
	elif mk[c2] != 0:
		for j in range(1, 7):
			if j == cl or j + cl == 7:
				continue
			if vis[c2, j]:
				a = dp[c2, j]
			else:
				a = solve(c2, j, dp, mk, vis, p)
			s = (s + a) % p
	else:
		vis[i, c] = 1
		return 1
	dp[i, cl] = s
	vis[i, cl] = 1
	return s
color = ['', 'w', 'g', 'r', 'o', 'b', 'y']
mk = defaultdict(lambda : 0)
dp = defaultdict(lambda : 0)
vis = defaultdict(lambda : 0)
m = 0
for i in range(n):
	st = ist().split()
	x = int(st[0])
	c = color.index(st[1][0])
	dp[x, c] = 1
	if mk[x] == 0:
		m += 1
	mk[x] = -1
	x = x // 2
	while x > 0:
		if mk[x] == 0:
			m += 1
			mk[x] = 1
		x = x // 2
s = 0
for i in range(1, 7):
	s += solve(1, i, dp, mk, vis, p)
	s %= p
y = powr(4, tot - m)
print(s * y % p)