Keyboard Purchase (Codeforces 1238E)
Tags: DP, bitmasks

You have a password which you often type — a string $$$s$$$ of length $$$n$$$. Every character of this string is one of the first $$$m$$$ lowercase Latin letters.Since you spend a lot of time typing it, you want to buy a new keyboard.A keyboard is a permutation of the first $$$m$$$ Latin letters. For example, if $$$m = 3$$$, then there are six possible keyboards: abc, acb, bac, bca, cab and cba.Since you type your password with one finger, you need to spend time moving your finger from one password character to the next. The time to move from character $$$s_i$$$ to character $$$s_{i+1}$$$ is equal to the distance between these characters on keyboard. The total time you have to spend typing the password with a keyboard is called the slowness of this keyboard.More formaly, the slowness of keyboard is equal to $$$\sum\limits_{i=2}^{n} |pos_{s_{i-1}} - pos_{s_i} |$$$, where $$$pos_x$$$ is position of letter $$$x$$$ in keyboard.For example, if $$$s$$$ is aacabc and the keyboard is bac, then the total time of typing this password is $$$|pos_a - pos_a| + |pos_a - pos_c| + |pos_c - pos_a| + |pos_a - pos_b| + |pos_b - pos_c|$$$ = $$$|2 - 2| + |2 - 3| + |3 - 2| + |2 - 1| + |1 - 3|$$$ = $$$0 + 1 + 1 + 1 + 2 = 5$$$.Before buying a new keyboard you want to know the minimum possible slowness that the keyboard can have. 

Input: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5, 1 \le m \le 20$$$).The second line contains the string $$$s$$$ consisting of $$$n$$$ characters. Each character is one of the first $$$m$$$ Latin letters (lowercase).

Output: Print one integer – the minimum slowness a keyboard can have.

Note: The first test case is considered in the statement.In the second test case the slowness of any keyboard is $$$0$$$.In the third test case one of the most suitable keyboards is bacd.

Sample Inputs:
6 3
aacabc

6 4
aaaaaa

15 4
abacabadabacaba

Sample Outputs:
5

0

16

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
INF = 10 ** 9
(n, m) = [int(item) for item in input().split()]
s = input().rstrip()
adj_in_subset = [0] * (1 << m)
ord_a = ord('a')
for (c1, c2) in zip(s, s[1:]):
    c1 = ord(c1) - ord_a
    c2 = ord(c2) - ord_a
    if c1 != c2:
        adj_in_subset[(1 << c1) + (1 << c2)] += 1
for i in range(m):
    for j in range(1 << m):
        if j & 1 << i:
            adj_in_subset[j] += adj_in_subset[j ^ 1 << i]
total_adj = adj_in_subset[-1]
dp = [INF] * (1 << m)
dp[0] = 0
for i in range(1 << m):
    for j in range(m):
        if i & 1 << j:
            continue
        cost = total_adj - adj_in_subset[i] - adj_in_subset[~i]
        dp[i | 1 << j] = min(dp[i | 1 << j], dp[i] + cost)
print(dp[-1])

Solution (Python):
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
    return map(int, sys.stdin.readline().rstrip().split())

def RLL():
    return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
    return int(input())

def comb(n, m):
    return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
    return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
    return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def cord(c):
    return ord(c) - ord('a')

def main():
    (n, m) = RL()
    s = input()
    ct = [0] * (1 << m)
    for i in range(n - 1):
        (now, nex) = (cord(s[i]), cord(s[i + 1]))
        if now == nex:
            continue
        ct[1 << now | 1 << nex] += 1
    for i in range(m):
        for j in range(1 << m):
            if 1 << i & j:
                ct[j] += ct[1 << i ^ j]
    dp = [INF] * (1 << m)
    dp[0] = 0
    for i in range(1 << m):
        for j in range(m):
            if i & 1 << j == 0:
                sm = ct[-1] - ct[i] - ct[~i]
                dp[i | 1 << j] = min(dp[i | 1 << j], dp[i] + sm)
    print(dp[-1])
if __name__ == '__main__':
    main()

Solution (Python):
(n, m) = map(int, input().split())
a = list(map(str, input().strip()))
dp = [10 ** 10] * (1 << 20)
cnt = [0] * (1 << 20)

def get(x):
    return 1 << ord(x) - ord('a')
for (i, v) in enumerate(a):
    if i:
        cnt[get(a[i]) | get(a[i - 1])] += 1
for i in range(m):
    for j in range(1 << m):
        if 1 << i & j:
            cnt[j] += cnt[j ^ 1 << i]
dp[0] = 0
for i in range(1 << m):
    for j in range(m):
        if not i & 1 << j:
            dp[i | 1 << j] = min(dp[i | 1 << j], dp[i] + n - 1 - cnt[i | 1 << j] - cnt[(1 << m) - 1 - (i | 1 << j)])
print(dp[(1 << m) - 1])