This page is still under construction.

Parts of this page are still being built. What you see may change.

Rats

Time limit0.75sMemory limit256 MB

Summary
Given an infinite periodic string A and a set S of strings, find the minimum number of strings from S whose concatenation forms a string B that tiles the line identically to A.
Level

Hard8 of 10

Topics
String, Graph, Shortest path, String matching
Solved
No attempts yet

Problem

You are given an infinite line covered with a periodically repeating string AA. There are infinitely many concatenated copies of the string AA on the line. The line has no beginning and no end. You are also given a set SS of MM strings. You must build a new string BB by concatenating strings from SS. The string BB must satisfy the following conditions:

  • After covering a new empty infinite line with infinitely many concatenations of the string BB, the line must be identical to the line covered with AA.
  • If there are several valid strings BB or several valid ways to build BB, choose BB and its construction that use the fewest strings from SS.

You may use the same string from SS several times, but each use counts as a new string. You may concatenate the strings in any order, but you may not change the order of letters inside a string. If no string BB can be built, print −1-1.

Input

  • The first line contains the string AA (1≤∣A∣≤500)(1\leq |A| \leq 500).
  • The second line contains the integer MM (1≤M≤105)(1 \leq M \leq 10^5), the number of strings in the set SS.
  • Each of the next MM lines contains one string from SS. The ii-th line contains the string LiL_i (1≤∣Li∣≤∣A∣)(1 \leq |L_i| \leq |A|).
  • The sum of the lengths of the strings in SS is at most 10610^6 (∑i=1M∣Li∣≤106)(\sum_{i=1}^{M} |L_i| \leq 10^6).

Output

Print one integer: the minimum number of strings from SS needed to build the string BB.

Hint

You can use one string "b" and two strings "a" to build BB = "aba":

  • ...baabaabaabaa...
  • .....abaabaabaaba...

Examples1

  1. Example 1

    Input
    baabaa
    3
    a
    b
    c
    
    Expected output
    3