Tyndex.Brome (Codeforces 62B)
Tags: Implement, binary search

Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules:  for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible.  if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck!

Input: The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105.

Output: On each n line of the output file print a single number: the value of the error function when the current potential address is chosen.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).


Sample Inputs:
2 10
codeforces
codeforces
codehorses

9 9
vkontakte
vcontacte
vkontrakte
vkollapse
vkrokodile
vtopke
vkapuste
vpechke
vk
vcodeforcese

Sample Outputs:
0
12

18
14
36
47
14
29
30
0
84

Solution (Python):
from bisect import bisect_left
(n, k) = map(int, input().split())
q = 'abcdefghijklmnopqrstuvwxyz'
a = {i: [] for i in q}
for (i, j) in enumerate(input()):
    a[j].append(i)

def g(t):
    return [(t[i] + t[i - 1]) // 2 for i in range(1, len(t))]
c = {i: g(a[i]) for i in q}

def f():
    global a, c
    (s, t) = (0, input())
    d = len(t)
    for (i, j) in enumerate(t):
        if a[j]:
            if c[j]:
                s += abs(i - a[j][bisect_left(c[j], i)])
            else:
                s += abs(i - a[j][0])
        else:
            s += d
    return str(s)
print('\n'.join((f() for i in range(n))))

Solution (Python):
def search(val):
    l = 0
    r = 1
    while l <= r:
        pass

def calc_f(arr, val):
    n = len(arr)
    l = 0
    r = n - 1
    last_less = False
    while l <= r:
        m = l + (r - l) // 2
        if arr[m] < val:
            l = m + 1
            last_less = True
        elif arr[m] > val:
            r = m - 1
            last_less = False
        else:
            return abs(val - arr[m])
    if last_less:
        nearest = (l, l - 1)
    else:
        nearest = (r, r + 1)
    min_diff = 10 ** 6
    for v in nearest:
        if 0 <= v < n:
            min_diff = min(min_diff, abs(val - arr[v]))
    return min_diff

def main():
    n = int(input().split()[0])
    s = input()
    d = {}
    for (i, char) in enumerate(s):
        arr = d.get(char, [])
        arr.append(i)
        d[char] = arr
    for i in range(n):
        c = input()
        nc = len(c)
        f = 0
        for (j, char) in enumerate(c):
            if char not in d:
                f += nc
            else:
                f += calc_f(d[char], j)
        print(f)
if __name__ == '__main__':
    main()

Solution (Python):
def g(t):
    return [(t[i] + t[i - 1]) // 2 for i in range(1, len(t))] + [1000000]

def h(a, b, c):
    j = s = 0
    for i in b:
        while i > c[j]:
            j += 1
        s += abs(i - a[j])
    return s
(n, k) = map(int, input().split())
q = 'abcdefghijklmnopqrstuvwxyz'
(s, a) = (0, {i: [] for i in q})
for (i, j) in enumerate(input()):
    a[j].append(i)
c = {i: g(a[i]) for i in q}

def f():
    (s, b) = (0, {i: [] for i in q})
    t = input()
    for (i, j) in enumerate(t):
        b[j].append(i)
    for i in q:
        if b[i]:
            if a[i]:
                s += h(a[i], b[i], c[i])
            else:
                s += len(t) * len(b[i])
    return str(s)
print('\n'.join((f() for i in range(n))))