LCS Again (Codeforces 578D)
Tags: Greedy, dp

You are given a string S of length n with each character being one of the first m lowercase English letters. Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1.Recall that LCS of two strings S and T is the longest string C such that C both in S and T as a subsequence.

Input: The first line contains two numbers n and m denoting the length of string S and number of first English lowercase characters forming the character set for strings (1 ≤ n ≤ 100 000, 2 ≤ m ≤ 26).The second line contains string S.

Output: Print the only line containing the answer.

Note: For the first sample, the 6 possible strings T are: aab, aac, aba, aca, baa, caa. For the second sample, the 11 possible strings T are: aaa, aac, aba, abb, abc, aca, acb, baa, bab, caa, cab.For the third sample, the only possible string T is b.

Sample Inputs:
3 3
aaa

3 3
aab

1 2
a

10 9
abacadefgh

Sample Outputs:
6

11

1

789

Solution (Python):
def main():
    (n, m) = map(int, input().split())
    s = input()
    k = sum((s[i] != s[i - 1] for i in range(1, n))) + 1
    x = i = 0
    while i < n - 1:
        if s[i] != s[i + 1]:
            j = i
            while i + 2 < n and s[i] == s[i + 2]:
                i += 1
            j = i - j + 2
            x += j * (j - 1) // 2
        i += 1
    ans = k * (m * n - n) - x
    print(ans)
main()

Solution (Python):
def main():
    (n, m) = map(int, input().split())
    s = input()
    k = sum((s[i] != s[i - 1] for i in range(1, n))) + 1
    x = i = 0
    while i < n - 1:
        if s[i] != s[i + 1]:
            j = i
            while i + 2 < n and s[i] == s[i + 2]:
                i += 1
            j = i - j + 2
            x += j * (j - 1) // 2
        i += 1
    ans = k * (m * n - n) - x
    print(ans)
main()

Solution (Python):
if __name__ == '__main__':
    (N, M) = map(int, input().split())
    S = input().strip()
    (ans, cnt) = (0, 0)
    for i in range(N):
        if i > 0 and S[i] == S[i - 1]:
            continue
        ans += N * M - N + 1
        if i > 0:
            ans -= 2
            if i < N - 1 and S[i - 1] == S[i + 1]:
                cnt += 1
                ans -= cnt
            else:
                cnt = 0
    print(ans - 1)