Problem:
 Score : 600 points    Problem Statement  In Dwango Co., Ltd., there is a content distribution system named 'Dwango Media Cluster', and it is called 'DMC' for short. The name 'DMC' sounds cool for Niwango-kun, so he starts to define DMC-ness of a string.  Given a string S of length N and an integer k  (k \geq 3) ,
he defines the k -DMC number of S as the number of triples (a, b, c) of integers that satisfy the following conditions:   0 \leq a < b < c \leq N - 1  S[a] = D  S[b] = M  S[c] = C  c-a < k   Here S[a] is the a -th character of the string S . Indexing is zero-based, that is, 0 \leq a \leq N - 1 holds.  For a string S and Q integers k_0, k_1, ..., k_{Q-1} , calculate the k_i -DMC number of S for each i  (0 \leq i \leq Q-1) .      Constraints   3 \leq N \leq 10^6  S consists of uppercase English letters  1 \leq Q \leq 75  3 \leq k_i \leq N  All numbers given in input are integers         Input  Input is given from Standard Input in the following format:  N  S  Q  k_{0}  k_{1}  ...  k_{Q-1}       Output  Print Q lines.
The i -th line should contain the k_i -DMC number of the string S .        Sample Input 1  18
DWANGOMEDIACLUSTER
1
18      Sample Output 1  1  (a,b,c) = (0, 6, 11) satisfies the conditions. Strangely, Dwango Media Cluster does not have so much DMC-ness by his definition.       Sample Input 2  18
DDDDDDMMMMMCCCCCCC
1
18      Sample Output 2  210  The number of triples can be calculated as 6\times 5\times 7 .       Sample Input 3  54
DIALUPWIDEAREANETWORKGAMINGOPERATIONCORPORATIONLIMITED
3
20 30 40      Sample Output 3  0
1
2  (a, b, c) = (0, 23, 36), (8, 23, 36) satisfy the conditions except the last one, namely, c-a < k_i . By the way, DWANGO is an acronym for "Dial-up Wide Area Network Gaming Operation".       Sample Output 4  30
DMCDMCDMCDMCDMCDMCDMCDMCDMCDMC
4
5 10 15 20      Sample Output 4  10
52
110
140

Solution (Python):
from collections import deque

N = int(input())
S = input()
Q = int(input())
K = list(map(int, input().split()))

for k in K:
    res = 0
    d = 0
    m = 0
    dm = 0
    for i in range(N):
        if S[i] == 'D':
            d += 1
        elif S[i] == 'M':
            dm += d
            m += 1
        elif S[i] == 'C':
            res += dm
        if i + 1 - k >= 0:
            if S[i + 1 - k] == 'D':
                d -= 1
                dm -= m
            elif S[i + 1 - k] == 'M':
                m -= 1

    print(res)

Solution (Python):
import sys
input = sys.stdin.readline

def main():
    N = int(input())
    S = input().rstrip()
    Q = int(input())
    k = list(map(int, input().split()))

    for l in k:
        D = 0
        M = 0
        tmp = 0
        ans = 0
        for i in range(N):
            if i >= l:
                if S[i-l] == 'D':
                    tmp -= M
                    D -= 1
                if S[i-l] == 'M':
                    M -= 1
            if S[i] == 'D':
                D += 1
            if S[i] == 'M':
                M += 1
                tmp += D
            if S[i] == 'C':
                ans += tmp
        print(ans)

main()

Solution (Python):
N,S,Q,*k = open(0).read().split()
N,Q = map(int, (N,Q))
K = map(int, k)
for k in K:
  D = 0
  M = 0
  DM = 0
  DMC = 0
  for i in range(k):
    if S[i]=='D':
      D += 1
    elif S[i]=='M':
      DM += D
      M += 1
    elif S[i]=='C':
      DMC += DM
  for i in range(N-k):
    if S[i]=='D':
      DM -= M
      D -= 1
    elif S[i]=='M':
      M -= 1
    if S[i+k]=='D':
      D += 1
    elif S[i+k]=='M':
      DM += D
      M += 1
    elif S[i+k]=='C':
      DMC += DM
  print(DMC)

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]

mod = 1000000007


n = I()
s = S()
q = I()
def f(k):
    cnt = [0, 0, 0] 
    ans = 0
    for i in range(n):
        if i - k >= 0:
            if s[i - k] == 'D':
                cnt[2] -= cnt[1]
                cnt[0] -= 1
            elif s[i - k] == 'M':
                cnt[1] -= 1
        if s[i] == 'D':
            cnt[0] += 1
        elif s[i] == 'M':
            cnt[1] += 1
            cnt[2] += cnt[0]
        elif s[i] == 'C':
            ans += cnt[2]
    return ans

K = LI()
for i in range(q):
    print(f(K[i]))

Solution (Python):
import numpy as np

N = int(input())
S = np.array(list(input()))
Q = int(input())
K = list(map(int, input().split()))


D_idx = S == 'D'
M_idx = S == 'M'
C_idx = S == 'C'

num_d = D_idx.cumsum(dtype=int)
num_m = M_idx.cumsum(dtype=int)

def count_DMC(k):
  _num_d = num_d.copy()
  _num_d[k:] = _num_d[k:] - _num_d[:-k] 
  _num_m = num_m.copy()
  _num_m[k:] = _num_m[k:] - _num_m[:-k] 
  num_dm = _num_d * M_idx 
  num_dm[k:] -= D_idx[:-k] * _num_m[k-1:-1]
  return (num_dm.cumsum(dtype=int) * C_idx).sum()


for k in K:
  print(count_DMC(k))

Solution (Python):
import sys

input = sys.stdin.readline

def main():
    n = int(input())
    sl = input()
    q = int(input())
    kl = tuple(map(int,input().split()))

    for k in kl:
        

        d = m = dm = ans = 0
        for i in range(n):
            if i - k >= 0:
                if sl[i-k] == "D":
                    d -= 1
                    dm -= m
                if sl[i-k] == "M":
                    m -= 1
            if sl[i] == "D":
                d += 1
            if sl[i] == "M":
                m += 1
                dm += d
            if sl[i] == "C":
                ans += dm

        print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
import sys
input = sys.stdin.readline

def main():
    N = int(input())
    S = input()
    Q = int(input())
    x = tuple(map(int,input().split()))
    for k in x:
        d,m,dm,dmc = 0,0,0,0
        for i in range(N):
            if S[i] == "D":
                d += 1
            elif S[i] == "M":
                m += 1
                dm += d
            elif S[i] == "C":
                dmc += dm
            if i >= k-1:
                if S[i-k+1] == "D":
                    dm -= m
                    d -= 1
                elif S[i-k+1] == "M":
                    m -= 1
        print(dmc)
    
if __name__ == "__main__":
    main()

Solution (Python):
import sys

input = sys.stdin.readline
N = int(input())
S = input().rstrip()
Q = int(input())
K = list(map(int, input().split()))

ds = [0] * N
ms = [0] * N
dms = [0] * N
cpos = []
for i, c in enumerate(S):
    if i > 0:
        ds[i] += ds[i - 1]
        ms[i] += ms[i - 1]
        dms[i] += dms[i - 1]
    if c == "D":
        ds[i] += 1
    elif c == "M":
        ms[i] += 1
    elif c == "C" and i > 0 and dms[i - 1] > 0:
        cpos.append(i)

    if i > 0 and c == "M":
        dms[i] += ds[i - 1]

for k in K:
    ans = 0
    for i in cpos:
        ans += dms[i - 1]
        if i - k >= 0:
            ans -= dms[i - k] + (ms[i - 1] - ms[i - k]) * ds[i - k]
    print(ans)

Solution (Python):
import sys
def main():
    input = sys.stdin.readline
    N=int(input())
    S=input()
    Q=int(input())
    *K,=map(int, input().split())

    for k in K:
        ans = 0
        d,m,dm=0,0,0
        j=0
        for i in range(N):
            if i-j == k:
                if S[j]=='D':
                    d -= 1
                    dm -= m
                elif S[j]=='M':
                    m -= 1
                j += 1

            if S[i] == 'D':
                d += 1
            elif S[i] == 'M':
                m += 1
                dm += d
            elif S[i] == 'C':
                ans += dm
        print(ans)

if __name__ == '__main__':
    main()

Solution (Python):

from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n = I()
    s = input()
    q = I()
    K = LI()
    for k in K:
        fa = fb = ok = 0
        ans = 0
        for i in range(k):
            if s[i] == "D":
                fa += 1
            elif s[i] == "M":
                fb += 1
                ok += fa
            elif s[i] == "C":
                ans += ok
        for i in range(k,n):
            pi = s[i-k]
            if pi == "D":
                fa -= 1
                ok -= fb
            elif pi == "M":
                fb -= 1
            if s[i] == "D":
                fa += 1
            elif s[i] == "M":
                fb += 1
                ok += fa
            elif s[i] == "C":
                ans += ok
        print(ans)
    return


if __name__ == "__main__":
    solve()

Solution (Python):
import sys
input = sys.stdin.readline

n=int(input())
s=input().rsplit()[0]

def calc(k):
	D=M=DM=DMC=0
	for i in range(n):
		if k<=i:
			if s[i-k]=="D":
				D-=1
				DM-=M
			elif s[i-k]=="M":
				M-=1
		if s[i]=="D":
			D+=1
		elif s[i]=="M":
			M+=1
			DM+=D
		elif s[i]=="C":
			DMC+=DM
	return DMC

q=int(input())
*k,=map(int,input().split())
ans=[calc(x) for x in k]
print(*ans,sep="\n")

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

import numpy as np

N = int(readline())
S = np.frombuffer(readline().rstrip(),'S1')
Q = int(readline())
query = map(int,read().split())

isD = S == b'D'
isM = S == b'M'
isC = S == b'C'

cumD = isD.cumsum(dtype=np.int64)
cumM = isM.cumsum(dtype=np.int64)

def F(K):
    """
    ・Cごとに数える。
    ・そのためには(i-K,i] 内のDMの個数を調べる（負インデックスには関係ない文字があると思っておく）
    ・区間内のDの個数、Mの個数が取得できれば、差分が取得できるので最後に累積和
    """
    
    D = cumD.copy(); D[K:] -= cumD[:-K]
    M = cumM.copy(); M[K:] -= cumM[:-K]
    
    DM = isM * D
    
    DM[K:] -= isD[:-K] * M[K-1:-1]
    np.cumsum(DM,out=DM)
    
    return DM[isC].sum()

print('\n'.join(str(F(K)) for K in query))

Solution (Python):
import sys
input = sys.stdin.readline

def main():
    N = int(input())
    S = input()
    Q = int(input())
    x = tuple(map(int,input().split()))
    for k in x:
        d,m,dm,dmc = 0,0,0,0
        for i in range(N):
            if S[i] == "D":
                d += 1
            elif S[i] == "M":
                m += 1
                dm += d
            elif S[i] == "C":
                dmc += dm
            if i >= k-1:
                if S[i-k+1] == "D":
                    dm -= m
                    d -= 1
                elif S[i-k+1] == "M":
                    m -= 1
        print(dmc)
    
if __name__ == "__main__":
    main()

Solution (Python):
import sys
input = sys.stdin.readline

def main():
    N = int(input())
    S = input()
    Q = int(input())
    x = tuple(map(int,input().split()))
    for k in x:
        d = 0
        m = 0
        dm = 0
        dmc = 0
        for i in range(N):
            if S[i] == "D":
                d += 1
            elif S[i] == "M":
                m += 1
                dm += d
            elif S[i] == "C":
                dmc += dm
            if i >= k-1:
                if S[i-k+1] == "D":
                    dm -= m
                    d -= 1
                elif S[i-k+1] == "M":
                    m -= 1
        print(dmc)
    
if __name__ == "__main__":
    main()

Solution (Python):
import sys
input = sys.stdin.readline

def main():
    N = int(input())
    S = input()
    Q = input()
    x = tuple(map(int,input().split()))
    for k in x:
        d,m,dm,dmc = 0,0,0,0
        for i in range(N):
            st = S[i]
            if st == "D":
                d += 1
            elif st == "M":
                m += 1
                dm += d
            elif st == "C":
                dmc += dm
            if i >= k-1:
                if S[i-k+1] == "D":
                    dm -= m
                    d -= 1
                elif S[i-k+1] == "M":
                    m -= 1
        print(dmc)
    
if __name__ == "__main__":
    main()

Solution (Python):
import sys


def main():
    N = int(input())
    S = input()
    Q = input()
    x = tuple(map(int,input().split()))
    for k in x:
        d,m,dm,dmc = 0,0,0,0
        for i in range(N):
            st = S[i]
            if st == "D":
                d += 1
            elif st == "M":
                m += 1
                dm += d
            elif st == "C":
                dmc += dm
            if i >= k-1:
                if S[i-k+1] == "D":
                    dm -= m
                    d -= 1
                elif S[i-k+1] == "M":
                    m -= 1
        print(dmc)
    
if __name__ == "__main__":
    main()

Solution (Python):
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))



N = I()
S = list(input())
Q = I()
k = LI()

cumD = [0]*N
cumM = [0]*N
cumDM = [0]*N

cumD[0] = 1 if S[0] == 'D' else 0
cumM[0] = 1 if S[0] == 'M' else 0

Clist = []
for i in range(1,N):
    cumD[i] = cumD[i-1]
    cumM[i] = cumM[i-1]
    cumDM[i] = cumDM[i-1]
    if S[i] == 'D':
        cumD[i] += 1
        continue
    if S[i] == 'M':
        cumM[i] += 1
        cumDM[i] += cumD[i-1]
        continue
    if S[i] == 'C':
        Clist.append(i)

for j in range(Q):
    ans = 0
    for i in Clist:
        if i-k[j] >= 0:
            ans += cumDM[i-1] - (cumD[i-k[j]])*(cumM[i-1]-cumM[i-k[j]]) - cumDM[i-k[j]]
        else:
            ans += cumDM[i-1]
    print(ans)

Solution (Python):
import sys
import numpy as np

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
S = np.array(list('_' + sr()))
Q = ir()
K = lr()
isD = (S == 'D')
isM = (S == 'M')
isC = (S == 'C')
cumD = isD.cumsum()
cumM = isM.cumsum()

for k in K:
    x = cumD.copy()
    x[k:] -= cumD[:-k]
    x *= isM
    x[k+1:] -= isD[1:-k] * (cumM[k:-1] - cumM[:-k-1])
    answer = (x.cumsum() * isC).sum()
    print(answer)

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline
    N = int(input())
    S = input()
    _ = int(input())
    K = [int(i) for i in input().split()]

    def solve(k):
        cd = 0
        cm = 0
        cdm = 0
        ans = 0
        for i in range(N):
            if S[i] == 'D':
                cd += 1
            elif S[i] == 'M':
                cm += 1
                cdm += cd
            elif S[i] == 'C':
                ans += cdm
            if k - 1 <= i:
                if S[i-k+1] == 'D':
                    cdm -= cm
                    cd -= 1
                if S[i-k+1] == 'M':
                    cm -= 1
        return ans

    for k in K:
        print(solve(k))


if __name__ == '__main__':
    main()

Solution (Python):
import sys
input=sys.stdin.readline

n=int(input())
s=[ord(i)for i in input()]
t=[-1]*n
for i in range(n):
  if s[i]==68:
    t[i]=0
  elif s[i]==77:t[i]=1
  elif s[i]==67:t[i]=2

def solve(k):
  dd=mm=dm=dmc=0
  for i in range(n):
    if t[i]==0:dd+=1
    if i>=k and t[i-k]==0:dm-=mm;dd-=1
    if t[i]==1:dm+=dd;mm+=1
    if i>=k and t[i-k]==1:mm-=1
    if t[i]==2:dmc+=dm
  return dmc

q=int(input())
k=list(map(int,input().split()))
for i in k:print(solve(i))

Solution (Python):
import sys

def solve():
    input = sys.stdin.readline
    N = int(input())
    S = input().strip("\n")
    Q = int(input())
    K = [int(k) for k in input().split()]
    for i, k in enumerate(K):
        Ans = 0
        NumD = 0
        NumM = 0
        NumDM = 0
        for i in range(N):
            if S[i] == "D": NumD += 1
            elif S[i] == "M": 
                NumM += 1
                NumDM += NumD
            if i >= k:
                if S[i - k] == "D":
                    NumD -= 1
                    NumDM -= NumM
                elif S[i - k] == "M": NumM -= 1
            if S[i] == "C": Ans += NumDM
        print(Ans)


    return 0

if __name__ == "__main__":
    solve()

Solution (Python):
def solve():
    N = int(input())
    Ss = input()
    Q = int(input())
    ks = list(map(int, input().split()))

    anss = []
    for k in ks:
        numD = numM = numDM = numDMC = 0
        for i in range(N):
            S = Ss[i]
            if S == 'D':
                numD += 1
            elif S == 'M':
                numM += 1
                numDM += numD
            elif S == 'C':
                numDMC += numDM

            if i >= k-1:
                S = Ss[i-k+1]
                if S == 'D':
                    numD -= 1
                    numDM -= numM
                elif S == 'M':
                    numM -= 1

        anss.append(numDMC)

    print('\n'.join(map(str, anss)))


solve()

Solution (Python):
import sys
input=sys.stdin.readline

def main():
    n=int(input())
    l=input()
    q=int(input())
    kl=tuple(map(int,input().split()))
    for k in kl:
        d=0
        m=0
        dm=0
        ans=0
        for j in range(n):
            if l[j]=='D':
                d+=1
            elif l[j]=='M':
                m+=1
                dm+=d
            elif l[j]=='C':
                ans+=dm
            if j>=k-1:
                if l[j-k+1]=='D':
                    dm-=m
                    d-=1
                elif l[j-k+1]=='M':
                    m-=1
        print(ans)
if __name__=='__main__':
    main()

Solution (Python):
import sys
input=sys.stdin.readline
n=int(input())
l=input()
q=int(input())
kl=tuple(map(int,input().split()))
for k in kl:
    d=0
    m=0
    dm=0
    ans=0
    for j in range(n):
        if l[j]=='D':
            d+=1
        elif l[j]=='M':
            m+=1
            dm+=d
        elif l[j]=='C':
            ans+=dm
        if j>=k-1:
            if l[j-k+1]=='D':
                dm-=m
                d-=1
            elif l[j-k+1]=='M':
                m-=1
    print(ans)

Solution (Python):



def main():
    n = int(input())
    s = input()
    q = int(input())
    *ks, = map(int, input().split())

    for k in ks:
        cnt = 0
        d, m, dm = 0, 0, 0
        for i in range(k):
            char = s[i]
            if char == 'D':
                d += 1
            elif char == 'M':
                m += 1
                dm += d
            elif char == 'C':
                cnt += dm

        for i in range(k, n):
            p_char = s[i - k]
            char = s[i]
            if p_char == 'D':
                dm -= m
                d -= 1
            elif p_char == 'M':
                m -= 1

            if char == 'D':
                d += 1
            elif char == 'M':
                m += 1
                dm += d
            elif char == 'C':
                cnt += dm

        print(cnt)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())
S = list(input())[: -1]
Q = int(input())
qs = list(map(int, input().split()))
cs = [0] * (N + 1)
c = []
d = []
for i in range(N):
  cs[i + 1] = cs[i] + (S[i] == "M")
  if S[i] == "C": c.append(i)
  if S[i] == "D": d.append(i)
ccs = [0] * (N + 1)
ccounts = [0] * (N + 1)
for i in range(N):
  ccs[i + 1] = ccs[i] + cs[i] * (S[i] == "C")
  ccounts[i + 1] = ccounts[i] + (S[i] == "C")



for k in qs:
  res = 0
  for i in d:
    l = i
    r = min(N, i + k)
    res += max(0, ccs[r] - ccs[l] - cs[i] * (ccounts[r] - ccounts[l]))
  print(res)

Solution (Python):
def num(s,n,k):
  d,m,dm,dmc = 0,0,0,0
  for i in range(n,n*2):
    x,y = s[i],s[i-k]
    if y == 68:
      d -= 1
      dm -= m
    elif y == 77:
      m -= 1
    if x == 68:
      d += 1
    elif x == 77:
      m += 1
      dm += d
    elif x == 67:
      dmc += dm
  return dmc

def main():
  n = int(input())
  s = [0]*n + list(map(ord, list(input())))
  _ = input()
  l = list(map(int, input().split()))
  for k in l:
    print(num(s,n,k))

main()

Solution (Python):
def main():
    N = int(input())
    S = list(input())
    Q = int(input())
    K = tuple(map(int, input().split()))
    d_list = [0] * N
    m_list = [0] * N
    c_list = [0] * N
    M_list = [0] * N
    for index, s in enumerate(S):
        if s == 'D':
            d_list[index] += 1
        elif s == 'M':
            m_list[index] += d_list[index - 1]
            M_list[index] += 1
        elif s == 'C':
            c_list[index] += m_list[index - 1]
        d_list[index] += d_list[index - 1]
        m_list[index] += m_list[index - 1]
        c_list[index] += c_list[index - 1]
        M_list[index] += M_list[index - 1]



    for k in K:
        d = d_list[k - 1]
        m = m_list[k - 1]
        c = c_list[k - 1]
        M = M_list[k - 1]

        for index, x in enumerate(S[k:]):
            if S[index] == 'D':
                m -= M
                d -= 1
            elif S[index] == 'M':
                M -= 1

            if x == 'D':
                d += 1
            elif x == 'M':
                m += d
                M += 1
            elif x == 'C':
                c += m            
        print (c)                


if __name__ == "__main__":
    main()

Solution (Python):
N = int(input())
S = list(input())
Q = int(input())
K = list(map(int,input().split()))
DP = [[0,0,0]]
C = []
for i in range(N):
    q = DP[i][:]
    if S[i] == "D":
        q[0] += 1
    elif S[i] == "M":
        q[1] += 1
        q[2] += q[0]
    elif S[i] == "C":
        C.append(i+1)
    DP.append(q)

for k in K:
    ans = 0
    for c in C:
        if c < k:
            ans += DP[c][2]
        else:
            ans += DP[c][2] - DP[c-k][2] - DP[c-k][0]*(DP[c][1] - DP[c-k][1])
    print(ans)

Solution (Python):
N = int(input())
S = input().strip()
qn = int(input())
qs = list(map(int, input().split()))
dd,mm,cc = [0],[0],[0]
dd_append = dd.append
mm_append = mm.append
cc_append = cc.append
As = [0]*qn
d=m=dm=0
for i, w in enumerate(S):
    i += 1
    if w=="D":
        d+=1
    elif w == "M":
        m+=1
        dm+=d
    elif w == "C":
        for j, q in enumerate(qs):
            if i-q:
                ll = max(i-q, 0)
                As[j] += dm - cc[ll] - dd[ll]*(m-mm[ll])
            else:
                As[j] += dm
    dd_append(d)
    mm_append(m)
    cc_append(dm)
for a in As:
    print(a)

Solution (Python):
N = int(input())
S = input().strip()
qn = int(input())
qs = list(map(int, input().split()))
dd,mm,cc = [0],[0],[0]
As = [0]*qn
d=m=dm=0
for i, w in enumerate(S):
    i += 1
    if w=="D":
        d+=1
    elif w == "M":
        m+=1
        dm+=d
    elif w == "C":
        for j, q in enumerate(qs):
            ll = max(i-q, 0)
            As[j] += dm - cc[ll] - dd[ll]*(m-mm[ll])
    dd.append(d)
    mm.append(m)
    cc.append(dm)
for a in As:
    print(a)

Solution (Python):
N = int(input())
S = input().strip()
qn = int(input())
qs = list(map(int, input().split()))
dd,mm,cc = [0],[0],[0]
As = [0]*qn
d=m=dm=0
for i, w in enumerate(S):
    i += 1
    if w=="D":
        d+=1
    elif w == "M":
        m+=1
        dm+=d
    elif w == "C":
        for j, q in enumerate(qs):
            ll = max(i-q, 0)
            As[j] += dm - cc[ll] - dd[ll]*(m-mm[ll])
    dd.append(d)
    mm.append(m)
    cc.append(dm)
for a in As:
    print(a)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n = I()
    s = input()
    q = I()
    K = LI()
    for k in K:
        ans = 0
        sa = 0
        sb = 0
        ns = 0
        for i in range(n):
            if i >= k:
                j = i-k
                if s[j] == "D":
                    sa -= 1
                    ns -= sb
                elif s[j] == "M":
                    sb -= 1
            if s[i] == "D":
                sa += 1
            elif s[i] == "M":
                sb += 1
                ns += sa
            elif s[i] == "C":
                ans += ns
        print(ans)
    return


if __name__ == "__main__":
    solve()

Solution (Python):
N=int(input())
S=tuple(map(ord,input()))
Q=int(input())
K=map(int,input().split())
D,M,C=map(ord,'DMC')

for k in K:
    ans=0
    d=m=dm=0
    for i in range(min(k-1,N)):
        c=S[i]
        if c==D:
            d+=1
        elif c==M:
            m+=1
            dm+=d
        elif c==C:
            ans+=dm
    for i in range(k-1,N):
        c=S[i]
        if c==D:
            d+=1
        elif c==M:
            m+=1
            dm+=d
        elif c==C:
            ans+=dm
        c=S[i-(k-1)]
        if c==D:
            d-=1
            dm-=m
        elif c==M:
            m-=1
    print(ans)

Solution (Python):

import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, S, Q, K):

    for k in K:
        d = 0
        m = 0
        dm = 0
        ans = 0
        for i in range(N):
            if S[i] == 'D':
                d += 1
            elif S[i] == 'M':
                m += 1
                dm += d
            elif S[i] == 'C':
                ans += dm

            j = i-k+1
            if j < 0:
                continue

            if S[j] == 'D':
                d -= 1
                dm -= m
            elif S[j] == 'M':
                m -= 1
        print(ans)


def main():
    N = read_int()
    S = read_str()
    Q = read_int()
    K = read_int_n()
    (slv(N, S, Q, K))


if __name__ == '__main__':
    main()

Solution (Python):

import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

n=int(input())
s=input()
q=int(input())
Q=map(int,input().split())
A=[-1]*(n+1)
C=[-1]*(n+1)
data=[0]*(n+1)
for i,si in enumerate(s):
    if si == "D":
        A[i]=count
    elif si == "M":
        count+=1
    elif si == "C":
        C[i]=count


for k in Q:
    count = ans = 0
    a_num=0
    for i in range(n):
        if A[i]!=-1:
            a_num+=1
            count+=A[i]
        if i-k>=0 and A[i-k]!=-1:
            a_num-=1
            count-=A[i-k]
        if C[i]!=-1:
            ans+=a_num*C[i]-count
    print(ans)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = 1e10










def solve():
    n = II()
    s = input().rstrip()
    q = II()
    k = LI()
    for ki in k:
        ans = 0
        d = 0
        dm = 0
        m =0
        for i in range(n):
            if i >= ki:
                if s[-ki +i] == "D":
                    d -= 1
                    dm -= m
                elif s[-ki + i] == "M":
                    m -= 1
            if s[i] == "D":
                d += 1
            elif s[i] == "M":
                m += 1
                dm += d
            elif s[i] == "C":
                ans += dm
        print(ans)
    return



if __name__ == '__main__':
    solve()

Solution (Python):
import sys
input = sys.stdin.readline

N = int(input())
S = input()
Q = int(input())
k = list(map(int, input().split()))

for ki in k :
    ret = 0
    dp = [0] * 3
    for i in range(N) :
        if i >= ki :
            j = i - ki
            if S[j] == 'D' :
                dp[0] -= 1
                dp[2] -= dp[1]
            elif S[j] == 'M' :
                dp[1] -= 1

        if S[i] == 'D' :
            dp[0] += 1
        elif S[i] == 'M' :
            dp[1] += 1
            dp[2] += dp[0]
        elif S[i] == 'C' :
            ret += dp[2]
            
    print(ret)