Newspaper Headline (Codeforces 91A)
Tags: Greedy, strings

A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2?

Input: The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1 ≤ |s1| ≤ 104, 1 ≤ |s2| ≤ 106).

Output: If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2.


Sample Inputs:
abc
xyz

abcd
dabc

Sample Outputs:
-1

2

Solution (Python):
def slove():
    s = str(input())
    t = str(input())
    n = len(s)
    pos = [n] * 26
    nxt = [[0] * 26 for _ in range(n)]
    for k in range(2, 0, -1):
        for i in range(n - 1, -1, -1):
            nxt[i] = pos[:]
            pos[ord(s[i]) - ord('a')] = i
    ans = 1
    (i, j) = (0, 0)
    if t[0] == s[0]:
        j = 1
    while j < len(t):
        i2 = nxt[i][ord(t[j]) - ord('a')]
        if i2 == n:
            print('-1')
            return
        if i2 <= i:
            ans += 1
        i = i2
        j += 1
    print(ans)
    return
    print(ans)
    return
slove()

Solution (Python):
s1 = input()
s2 = input()

def run(s1, s2):
    if set(s2) - set(s1):
        print(-1)
        return
    pre = dict()
    for (i, c) in enumerate(s1):
        if c not in pre:
            pre[c] = i
    n = len(s1)
    q = [[] for _ in range(n)]
    for idx in range(n - 1, -1, -1):
        pre[s1[idx]] = idx
        q[idx] = dict(pre)
    (ans, idx) = (1, 0)
    for (tmp, c) in enumerate(s2):
        nxt_idx = q[idx][c]
        if nxt_idx < idx:
            ans += 1
        idx = (nxt_idx + 1) % n
        if idx == 0:
            ans += 1
    if idx == 0:
        ans -= 1
    print(ans)
run(s1, s2)

Solution (Python):
I = input
(s, z) = (I(), I())
(q, o, k, a) = ({*s}, len(s), {}, 1)
(l, x) = ([0] * o, -1)
if len(q | {*z}) != len(q):
    exit(print(-1))
for i in range(o - 1, -1, -1):
    l[i] = dict(k)
    k[s[i]] = i
l += [k]
for i in z:
    if i in l[x]:
        x = l[x][i]
    else:
        a += 1
        x = k[i]
print(a)