Kevin_K的flag回收录00(2018年问题求解与程序设计第二次练习"C. Bear and Compressing"题解)

Kevin_K edited 2 年，1 月前

C. Bear and Compressing

Time limit per test: 2.0 seconds
Memory limit: 512 MB

Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that, for the small dataset, he knows only first six letters of the English alphabet: a, b, c, d, e and f.

You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string a_i of length two and a string b_i of length one. No two of q possible operations have the same string a_i.

When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string a_i. Performing the i-th operation removes first two letters of s and inserts there a string b_i. See the notes section for further clarification.

You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don’t match any a_i.

Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string a. In how many ways can he choose the starting string to be able to get a? Remember that Limak can use only letters he knows.

Input

The first line contains two integers n and q — the length of the initial string and the number of available operations.

The next q lines describe the possible operations. The i-th of them contains two strings a_i and b_i (|a_i| = 2, |b_i| = 1). It’s guaranteed that a_i \ne a_j for i \ne j.

• For dataset SMALL: 2 \le n \le 6, 1 \le q \le 36, a_i, b_i consist of only first six lowercase English letters.
• For dataset MEDIUM: 2 \le n \le 10^5, 1 \le q \le 576, a_i, b_i can be any lowercase English letters.
• For dataset LARGE: Same as MEDIUM, except 2 \le n \le 10^{18}.

Output

Print the number of strings of length n that Limak will be able to transform to string a by applying only operations given in the input.

As the number can be very large, output it modulo 10^9+7.

分析

Python3 Code:

MOD = 1000000007
C = 26  # 字母个数.
lgn = 66

def mul(a, b):  # 矩阵乘法.
return [[sum([a[i][k] * b[k][j] for k in range(len(b))]) % MOD for j in range(len(b[0]))] for i in range(len(a))]

n, q = map(int, input().split())

# 初始化:
e = [[0 for j in range(C)] for i in range(C)]

# 输入B:
for i in range(q):
a, b = input().split()
e[ord(b[0]) - ord('a')][ord(a[0]) - ord('a')] += 1

# 记下Bn(n为2的幂)
ans = [e]
for i in range(lgn):
ans.append(mul(ans[-1], ans[-1]))

# res是答案.
res = [[0 if i else 1 for i in range(C)]]

# t是现在的基,n记得-1因为开始时就长1位.
t = 0
n -= 1
while n:
if n % 2:
res = mul(res, ans[t])  # 根据二进制决定是否乘矩阵.
n //= 2
t += 1

# 输出:
print(sum(res[0]) % MOD)