#abc344d. D - String Bags

D - String Bags

Score: 425425 points

问题描述

你最初有一个空字符串 SS
另外,有 1,2,,N1, 2, \dots, N 个袋子,每个袋子里包含一些字符串。
ii 个袋子包含 AiA_i 个字符串 Si,1,Si,2,,Si,AiS_{i,1}, S_{i,2}, \dots, S_{i,A_i}

你将对 i=1,2,,Ni = 1, 2, \dots, N 重复以下步骤:

  • 选择并执行以下两种操作之一:
    • 支付 11 日元,从第 ii 个袋子中精确选择一个字符串,并将其拼接到 SS 的末尾。
    • 什么也不做。

给定一个字符串 TT,找出使最终的 SS 等于 TT 所需的最小金额。
如果无法使最终的 SS 等于 TT,则输出 -1

以上为通义千问 qwen-max 翻译,仅供参考。

Problem Statement

You initially have an empty string SS.
Additionally, there are bags 1,2,,N1, 2, \dots, N, each containing some strings.
Bag ii contains AiA_i strings Si,1,Si,2,,Si,AiS_{i,1}, S_{i,2}, \dots, S_{i,A_i}.

You will repeat the following steps for i=1,2,,Ni = 1, 2, \dots, N:

  • Choose and perform one of the following two actions:
    • Pay 11 yen, select exactly one string from bag ii, and concatenate it to the end of SS.
    • Do nothing.

Given a string TT, find the minimum amount of money required to make the final SS equal TT.
If there is no way to make the final SS equal TT, print -1.

Constraints

  • TT is a string consisting of lowercase English letters with length between 11 and 100100, inclusive.
  • NN is an integer between 11 and 100100, inclusive.
  • AiA_i is an integer between 11 and 1010, inclusive.
  • Si,jS_{i,j} is a string consisting of lowercase English letters with length between 11 and 1010, inclusive.

Input

The input is given from Standard Input in the following format:

TT

NN

A1A_1 S1,1S_{1,1} S1,2S_{1,2} \dots S1,A1S_{1,A_1}

A2A_2 S2,1S_{2,1} S2,2S_{2,2} \dots S2,A2S_{2,A_2}

\vdots

ANA_N SN,1S_{N,1} SN,2S_{N,2} \dots SN,ANS_{N,A_N}

Output

Print the answer as an integer.

Sample Input 1

abcde
3
3 ab abc abcd
4 f c cd bcde
2 e de

Sample Output 1

2

For example, doing the following makes the final SS equal TT with two yen, which can be shown to be the minimum amount required.

  • For i=1i=1, select abc from bag 11 and concatenate it to the end of SS, making S=S= abc.
  • For i=2i=2, do nothing.
  • For i=3i=3, select de from bag 33 and concatenate it to the end of SS, making S=S= abcde.

Sample Input 2

abcde
3
2 ab abc
3 f c bcde
1 e

Sample Output 2

-1

There is no way to make the final SS equal TT, so print -1.

Sample Input 3

aaabbbbcccc
6
2 aa aaa
2 dd ddd
2 ab aabb
4 bbaa bbbc bbb bbcc
2 cc bcc
3 ccc cccc ccccc

Sample Output 3

4