Problem:


Score: 600 points

Problem Statement

How many strings can be obtained by applying the following operation on a string S exactly K times: "choose one lowercase English letter and insert it somewhere"?

The answer can be enormous, so print it modulo (10^9+7).

Constraints

K is an integer between 1 and 10^6 (inclusive).

S is a string of length between 1 and 10^6 (inclusive) consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

K
S

Output

Print the number of strings satisfying the condition, modulo (10^9+7).

Sample Input 1

5
oof

Sample Output 1

575111451

For example, we can obtain proofend, moonwolf, and onionpuf, while we cannot obtain oofsix, oofelevennn, voxafolt, or fooooooo.

Sample Input 2

37564
whydidyoudesertme

Sample Output 2

318008117



Sample input:
5
oof


Sample output:
575111451

Submission status: Accepted

Solution code:
MOD = 10 ** 9 + 7


def solveBrute(K, S):
    # On the i-th iteration, dp[j] counts all strings of length i which contains S[:j] as a subsequence

    N = len(S)
    dp = [0] * (N + 1)
    dp[0] = 1
    for i in range(N + K):
        nextDp = [0] * (N + 1)
        for j in range(N):
            nextDp[j] += dp[j] * 25
            nextDp[j + 1] += dp[j]
        nextDp[N] += dp[N] * 26

        dp = nextDp
        for j in range(N + 1):
            dp[j] %= MOD
        # print(dp)

    return dp[N]


def solveBrute2(K, S):
    import numpy as np

    def matrixPower(mat, k):
        assert k >= 0
        if k == 0:
            return np.eye(mat.shape[0], dtype=np.int64)
        if k == 1:
            return mat
        temp = matrixPower(mat, k // 2)
        ret = (temp @ temp) % MOD
        if k % 2:
            return (ret @ mat) % MOD
        return ret

    # For intution, can interpret the bruteforce as a matrix multiplication:
    # {{0, 0, 0, 1}} . MatrixPower[{{25, 0, 0, 0}, {1, 25, 0, 0}, {0, 1, 25, 0}, {0, 0, 1, 26}}, 8] . {{1}, {0}, {0}, {0}}
    # https://www.wolframalpha.com/input/?i=%7B%7B0%2C+0%2C+0%2C+1%7D%7D+.+MatrixPower%5B%7B%7B25%2C+0%2C+0%2C+0%7D%2C+%7B1%2C+25%2C+0%2C+0%7D%2C+%7B0%2C+1%2C+25%2C+0%7D%2C+%7B0%2C+0%2C+1%2C+26%7D%7D%2C+8%5D+.+%7B%7B1%7D%2C+%7B0%7D%2C+%7B0%7D%2C+%7B0%7D%7D

    N = len(S)

    mat = 25 * np.eye(N + 1, dtype=np.int64,)
    mat[N][N] += 1
    for i in range(N):
        mat[i + 1][i] = 1

    vec = np.zeros((N + 1, 1), dtype=np.int64)
    vec[0] = 1

    res = matrixPower(mat, N + K) @ vec
    return int(res[N]) % MOD


def solve(K, S):
    def modInverse(a, p):
        # Fermat's little theorem, a**(p-1) = 1 mod p
        return pow(a, p - 2, p)

    # Precompute all factorials
    fact = [1]
    for i in range(1, 2 * (10 ** 6) + 1):
        fact.append((fact[-1] * i) % MOD)

    def nCr(n, r, p=MOD):
        # Modulo binomial coefficients
        return (fact[n] * modInverse(fact[r], p) * modInverse(fact[n - r], p)) % p

    total = 0
    N = len(S)
    for i in range(N, N + K + 1):
        total += nCr(N + K, i) * pow(25, N + K - i, MOD)
        total %= MOD
    return total


(K,) = [int(x) for x in input().split()]
S = input()
ans = solve(K, S)
# assert ans == solveBrute(K, S) == solveBrute2(K, S)
print(ans)

Submission status: Accepted

Solution code:
import sys

def I(): return int(sys.stdin.readline().rstrip())
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし

K = I()
n = len(LS2())
mod = 10**9+7

# 完成図は、
# (S[0]以外からなる文字列)S[0](S[1]以外からなる文字列)S[1]…(S[n-1]以外からなる文字列)S[n-1](任意の文字列)
# この表記は一意
# 形式的冪級数で考えると,
# 求めたいものは (1-25x)^(-n)*(1-26x)^(-1) の x^K の係数であり、
# これは、(i+n-1)_C_(n-1)*25^i*26^(K-i) を i=0,…,K にわたって足し合わせたものである

C = [1]
for i in range(1,K+1):
    C.append((C[-1]*(i+n-1)*pow(i,mod-2,mod)) % mod)
# C[i] = (i+n-1)_C_(n-1)

ans = 0
for i in range(K+1):
    ans += C[i]*pow(25,i,mod)*pow(26,K-i,mod)
    ans %= mod

print(ans)

Submission status: Accepted

Solution code:
K=int(input())
S=input()
N=len(S)
mod=10**9+7

def cmb(n,r):
  global mod
  if r<0 or r>n:
    return 0
  return (g1[n]*g2[r]*g2[n-r])%mod

g1=[1,1]
g2=[1,1]
inv=[0,1]
for i in range(2,3000003):
  g1.append((g1[-1]*i)%mod)
  inv.append((-inv[mod%i]*(mod//i))%mod)
  g2.append((g2[-1]*inv[-1])%mod)
P=0
for i in range(N,N+K+1):
  P=(P+cmb(N+K,i)*pow(25,N+K-i,mod))%mod
print(P)

Submission status: Accepted

Solution code:
class comb():
  F = [1, 1]
  Fi = [1, 1]
  I = [0, 1]
  def __init__(self, num, mod):
    self.MOD = mod
    for i in range(2, num + 1):
      self.F.append((self.F[-1] * i) % mod)
      self.I.append(mod - self.I[mod % i] * (mod // i) % mod)
      self.Fi.append(self.Fi[-1] * self.I[i] % mod)
  def com(self, n, k):
    if n < k: return 0
    if n < 0 or k < 0: return 0
    return self.F[n] * (self.Fi[k] * self.Fi[n - k] % self.MOD) % self.MOD


K = int(input())
S = input()
MOD = 10 ** 9 + 7

N = K + len(S)
M = len(S)
com = comb(N + 1, MOD)

p25 = [1]
for i in range(N + 1):
  p25.append(p25[-1] * 25 % MOD)

ans = 0

for i in range(K + 1):
  t = M + i
  ans = (ans + p25[N - t] * com.com(N, t)) % MOD

print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

MOD = 10 ** 9 + 7


def main(K, N, MOD):
    def fact_table(N, MOD):
        inv = np.empty(N, np.int64)
        inv[0] = 0
        inv[1] = 1
        for n in range(2, N):
            q, r = divmod(MOD, n)
            inv[n] = inv[r] * (-q) % MOD
        fact = np.empty(N, np.int64)
        fact[0] = 1
        for n in range(1, N):
            fact[n] = n * fact[n - 1] % MOD
        fact_inv = np.empty(N, np.int64)
        fact_inv[0] = 1
        for n in range(1, N):
            fact_inv[n] = fact_inv[n - 1] * inv[n] % MOD
        return fact, fact_inv, inv

    fac, finv, _ = fact_table(2_000_010, MOD)
    f = np.zeros(K + 1, np.int64)
    f = fac[N - 1:K + N] * finv[N - 1] % MOD * finv[0:K + 1] % MOD

    x = 1
    for i in range(1, K + 1):
        x = (x * 25) % MOD
        f[i] = f[i] * x % MOD
    for i in range(1, K + 1):
        f[i] += f[i - 1] * 26
        f[i] %= MOD
    return f[-1]


if sys.argv[-1] == 'ONLINE_JUDGE':
    import numba
    from numba.pycc import CC
    i8 = numba.from_dtype(np.int64)
    signature = (i8, i8, i8)
    cc = CC('my_module')
    cc.export('main', signature)(main)
    cc.compile()

from my_module import main
K = int(readline())
N = len(read().rstrip())
print(main(K, N, MOD))

Submission status: Accepted

Solution code:
import sys


class Bigint:

    mod = 10**9 + 7

    def __init__(self, n):
        self.n = n % self.mod

    def __str__(self):
        return str(self.n)

    def __add__(self, other):
        ot = type(other)
        if ot == Bigint:
            return Bigint(self.n+other.n)
        elif ot == int:
            return Bigint(self.n+other)
        else:
            raise ValueError("Invalid type")

    def __iadd__(self, other):
        return self.__add__(other)

    def __sub__(self, other):
        ot = type(other)
        if ot == Bigint:
            o = other.n
        elif ot == int:
            o = other
        else:
            raise ValueError("Invalid type")
        #
        return Bigint(self.n - o)

    def __isub__(self, other):
        return self.__sub__(other)

    def __mul__(self, other):
        ot = type(other)
        if ot == Bigint:
            return Bigint(self.n*other.n)
        elif ot == int:
            return Bigint(self.n*other)
        else:
            raise ValueError("Invalid type")

    def __imul__(self, other):
        return self.__mul__(other)

    def __pow__(self, other):
        assert type(other) == int, "power should be integer"
        #
        if other < 0:
            return self ** (other % (self.mod-1))
        ret = Bigint(1)
        now = Bigint(self.n)
        while other > 0:
            if other % 2 == 0:
                pass
            else:
                ret *= now
            other //= 2
            now *= now
        return ret

    def __truediv__(self, other):
        ot = type(other)
        if ot == Bigint:
            o = other
        elif ot == int:
            o = Bigint(other)
        else:
            raise ValueError("Invalid type")

        self *= (o ** (o.mod-2))
        return self

    def __itruediv__(self, other):
        return self.__truediv__(other)


def _s(): return sys.stdin.readline().strip()


def _i(): return int(sys.stdin.readline().strip())


def main():
    k = _i()
    s = _s()
    n = len(s)

    fact = [Bigint(1)] * (n+k)
    for i in range(1, n+k):
        fact[i] = fact[i-1] * i

    ifact = [None] * (n+k)
    ifact[n+k-1] = fact[n+k-1] ** (-1)
    for i in range(n+k-2, -1, -1):
        ifact[i] = ifact[i+1] * (i+1)

    p = [Bigint(1)] * (k+1)
    q = [Bigint(1)] * (k+1)
    for i in range(1, k+1):
        p[i] = p[i-1] * 25
        q[i] = q[i-1] * 26

    nf = ifact[n-1]
    ret = Bigint(0)
    for i in range(k+1):
        k_ = k - i
        n_ = n - 1 + k_
        nck = fact[n_] * ifact[k_] * nf
        ret += (nck * p[k_] * q[i])

    return ret


if __name__ == "__main__":
    print(main())

Submission status: Accepted

Solution code:
K = int(input())
S = list(input())
MOD = 10**9 + 7
N = len(S)
M = K+N

#nCrは以下のやつ全てを使ってください
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]
 
gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]
 
def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

ans = 0
for i in range(N,M+1):
    ans += nCr(i-1,N-1)*pow(26,M-i,MOD) * pow(25,i-N,MOD)
    ans %= MOD
print(ans)

Submission status: Accepted

Solution code:
k = int(input())
s = input()
mod = 10**9 + 7

n = 2*10**6 + 1
factorial = [1]
inverse = [1]
pow25 = [1]
pow26 = [1]
for i in range(1, n+1):
    factorial.append(factorial[-1] * i % mod)
    inverse.append(pow(factorial[-1], mod - 2, mod))
    pow25.append((pow25[-1]*25)%mod)
    pow26.append((pow26[-1]*26)%mod)

def comb(n, r, mod):
    if n < r or r < 0: return 0
    elif r == 0: return 1
    return factorial[n] * inverse[r] * inverse[n - r] % mod

n = len(s)
length = k + n
ans = 0
for i in range(n, length+1):
    temp = 1
    temp *= comb(i-1, n-1, mod)
    temp %= mod
    temp *= pow25[i-n]
    temp %= mod
    temp *= pow26[length-i]
    temp %= mod
    ans += temp
    ans %= mod
print(ans)

Submission status: Accepted

Solution code:
k=int(input())
s=input()

mod=10**9+7

import sys
sys.setrecursionlimit(10**9)

def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p
p = mod #割る数
N = 2*(10 ** 6)  # N は必要分だけ用意する
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用
for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

ans=0

for i in range(k+1):
    ans = (ans+cmb(i+len(s)-1,i,mod)*pow(26,k-i,mod)*pow(25,i,mod)) % mod

    #print(end,len(s)+k-end,ans,cmb(end,len(s),mod),pow(25,end-len(s),mod),pow(26,len(s)+k-end,mod))

print(ans%mod)

Submission status: Accepted

Solution code:
g1 = [1, 1]
g2 = [1, 1]
inverse = [0, 1]
MOD = 10**9+7
for i in range(2, 2*10**6+1):
    g1.append((g1[-1] * i) % MOD)
    inverse.append((-inverse[MOD % i] * (MOD // i)) % MOD)
    g2.append((g2[-1] * inverse[-1]) % MOD)

def comb(n, r, mod=MOD):
    if r < 0 or r > n:
        return 0
    r = min(r, n - r)
    return g1[n] * g2[r] * g2[n-r] % mod

K = int(input())
S = input()
N = len(S)
NN = N + K
ans = 0
pow25 = [1]
pow26 = [1]
for i in range(K+1):
  pow25.append(pow25[-1]*25 % MOD)
  pow26.append(pow26[-1]*26 % MOD)

for i in range(K+1):
  n = NN - i
  ans = (ans + pow26[i]*pow25[n-N]*comb(n-1, N-1)) % MOD

print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(300000)

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI0(): return map(lambda s: int(s) - 1, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
def LMI0(): return list(map(lambda s: int(s) - 1, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')

class BinomialCoefficient(object):

    def __init__(self, N=510000, MOD=10**9+7):
        self.fac = [1, 1]
        self.finv = [1, 1]
        self.inv = [0, 1]
        self.MOD = MOD
        for i in range(2, N + 1):
            self.fac.append((self.fac[-1] * i) % MOD)
            self.inv.append((-self.inv[MOD % i] * (MOD // i)) % MOD)
            self.finv.append((self.finv[-1] * self.inv[-1]) % MOD)

    def comb(self, n, r):
        if r < 0 or n < r or r < 0:
            return 0
        return self.fac[n] * self.finv[r] * self.finv[n - r] % self.MOD

K = I()
S = input()

bi = BinomialCoefficient(N=10 ** 6 * 2 + 1)
ans = 0
# i := Snのindex
for i in range(len(S) - 1, len(S) + K):
    tail = len(S) + K - i - 1
    lans = bi.comb(i, len(S) - 1)
    lans = lans * pow(25, K - tail, MOD) % MOD
    lans = lans * pow(26, tail, MOD) % MOD
    ans = (ans + lans) % MOD
print(ans)

Submission status: Accepted

Solution code:
mod = 10**9+7
M = 2*10**6

fact = [1]*(M+1)
factinv = [1]*(M+1)
inv = [1]*(M+1)
for n in range(2,M+1):
    fact[n] = n*fact[n-1]%mod
    inv[n] = -inv[mod%n]*(mod//n)%mod
    factinv[n] = inv[n]*factinv[n-1]%mod

def comb(n,k):
    return fact[n]*factinv[k]*factinv[n-k]%mod

def main(K,S):
    n = len(S)
    ans = 0

    for k in range(K+1):
        ans += comb(n+k-1,k)*pow(25,k,mod)*pow(26,K-k,mod)
        ans %= mod
    print(ans)

if __name__ == '__main__':
    K = int(input())
    S = input()
    main(K,S)

Submission status: Accepted

Solution code:
k = int(input())
n = len(input())
p = 10**9 + 7
a = 1
fct = [a]
for i in range(1, n + k + 1):
    a = (a * i) % p
    fct.append(a)
b = pow(fct[-1], p - 2, p)
inv = [b]
for i in range(1, n + k + 1)[::-1]:
    b = (b * i) % p
    inv.append(b)
inv.reverse()
ans = 0
pow25, pow26 = [1], [1]
for i in range(1, k + 1):
    pow25.append((pow25[-1] * 25) % p)
    pow26.append((pow26[-1] * 26) % p)
for i in range(k + 1):
    c = fct[i + n - 1] * inv[i] * inv[n - 1]
    ans += pow25[i] * pow26[k - i] * c
    ans %= p
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque
def input(): return sys.stdin.readline().strip()
mod = 10**9+7

class Combination:
    """
    O(n)の前計算を1回行うことで，O(1)でnCr mod mを求められる
    n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
    使用例：
    comb = Combination(1000000)
    print(comb(5, 3))  # 10
    """
    def __init__(self, n_max, mod=10**9+7):
        self.mod = mod
        self.modinv = self.make_modinv_list(n_max)
        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def make_factorial_list(self, n):
        # 階乗のリストと階乗のmod逆元のリストを返す O(n)
        # self.make_modinv_list()が先に実行されている必要がある
        fac = [1]
        facinv = [1]
        for i in range(1, n+1):
            fac.append(fac[i-1] * i % self.mod)
            facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
        return fac, facinv

    def make_modinv_list(self, n):
        # 0からnまでのmod逆元のリストを返す O(n)
        modinv = [0] * (n+1)
        modinv[1] = 1
        for i in range(2, n+1):
            modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
        return modinv

comb = Combination(2 * 10**6)

def main():
    K = int(input())
    S = deque(input())
    L = len(S)
    """
    dpではなく単純に組み合わせ論だった。。。
    """
    ans = 0
    for x in range(K + 1):
        ans += comb(K - x + L - 1, L - 1) * pow(25, K - x, mod) * pow(26, x, mod)
        ans %= mod
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

k = I()
s = input()
n = len(s)

fact = [1] * (n + k + 1)
for i in range(1, n+k+1):
    fact[i] = i * fact[i-1]
    fact[i] %= mod
ans = 0
for i in range(n, n + k + 1):
    ret = fact[i-1] * pow(fact[n-1], mod-2, mod) * pow(fact[i-n], mod-2, mod) % mod
    ret *= pow(25, i - n, mod)
    ret %= mod
    ret *= pow(26, k + n - i, mod)
    ret %= mod
    ans += ret
    ans %= mod
print(ans)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


k = int(input())
s = input()
n = len(s)
M = 10**9+7

N = n+k # 必要なテーブルサイズ

def cmb(n, r, M):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return (g1[n] * g2[r] * g2[n-r]) % M

g1 = [None] * (N+1) # 元テーブル
g2 = [None] * (N+1) #逆元テーブル
inverse = [None] * (N+1) #逆元テーブル計算用テーブル
g1[0] = g1[1] = g2[0] = g2[1] = 1
inverse[0], inverse[1] = [0, 1] 

for i in range( 2, N + 1 ):
    g1[i] = ( g1[i-1] * i ) % M 
    inverse[i] = ( -inverse[M % i] * (M//i) ) % M # ai+b==0 mod M <=> i==-b*a^(-1) <=> i^(-1)==-b^(-1)*aより
    g2[i] = (g2[i-1] * inverse[i]) % M 

ans = 0
for i in range(n-1, n+k):
    ans += pow(25,i-n+1,M)*pow(26,n+k-i-1,M)*cmb(i,n-1,M)
    ans %= M
print(ans)

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    K = int(readline())
    S = readline().strip()

    COM_MAX = 2 * 10 ** 6

    fac, finv, inv = [0] * (COM_MAX + 1), [0] * (COM_MAX + 1), [0] * (COM_MAX + 1)
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1

    for i in range(2, COM_MAX + 1):
        fac[i] = fac[i - 1] * i % MOD
        inv[i] = MOD - inv[MOD % i] * (MOD // i) % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD

    def mod_com(n, r):
        if n < r:
            return 0
        if n < 0 or r < 0:
            return 0
        return fac[n] * (finv[r] * finv[n - r] % MOD) % MOD

    N = len(S)
    L = K + N

    ans = 0
    p25 = pow(25, K, MOD)
    inv25 = pow(25, MOD - 2, MOD)
    p26 = 1
    for i in range(K + 1):
        ans = (ans + mod_com(L - i - 1, N - 1) * p25 * p26) % MOD
        p25 = p25 * inv25 % MOD
        p26 = p26 * 26 % MOD

    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
k = int(input())
s = input()

def pre(n,MOD):
    f = 1
    factor = [1]
    for m in range(1,n+1):
        f *= m
        f %= MOD
        factor.append(f)
    inv = pow(f,MOD-2,MOD)
    invs = [1] * (n+1)
    for m in range(n,1,-1):
        inv *= m
        inv %= MOD
        invs[m-1] = inv
    return factor,invs

MOD = 10**9 + 7
n = len(s)
factor,invs = pre(n+k,MOD)
ans = 0
for i in range(k+1):
    temp = 1
    temp = (temp * factor[n-1+k-i] * invs[n-1] * invs[k-i]) % MOD
    temp = temp * pow(25,k-i,MOD) % MOD
    temp = temp * pow(26,i,MOD) % MOD
    ans = (ans + temp) % MOD
print(ans)

Submission status: Accepted

Solution code:
MOD = 10 ** 9 + 7
K = int(input())
M = len(input())
N = M + K

pow25 = [1] * (N + 1)
fac = [1] * (N + 1)
inv = [1] * (N + 1)
for x in range(1, N + 1):
    fac[x] = fac[x - 1] * x % MOD
    pow25[x] = pow25[x - 1] * 25 % MOD
inv[N] = pow(fac[N], MOD-2, MOD)
for x in range(N - 1, -1, -1):
    inv[x] = inv[x + 1] * (x + 1) % MOD

def binom(n, k):
    return fac[n] * inv[n - k] % MOD * inv[k] % MOD

ans = 0
for k in range(M, N + 1):
    ans += binom(N, k) * pow25[N - k] % MOD
    ans %= MOD
print(ans)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def comb_mod(n, r):
    res = 1
    r = min(n - r, r)

    for i in range(r):
        res *= (n - i)
        res %= MOD
        res *= pow((r - i), MOD - 2, MOD)

    return res


def main():
    k = int(readline())
    s = input()
    l = len(s)
    x = k + l

    comb = 1
    ans = 0
    for i in range(k + 1):
        ans += pow(26, k - i, MOD) * pow(25, i, MOD) * comb
        ans %= MOD
        comb *= (l + i)
        comb %= MOD
        comb *= pow(i + 1, MOD - 2, MOD)
        comb %= MOD

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

k = I()
s = input()
n = len(s)

fact = [1] * (n + k + 1)
for i in range(1, n+k+1):
    fact[i] = i * fact[i-1]
    fact[i] %= mod
ans = 0
for i in range(n, n + k + 1):
    ret = fact[i-1] * pow(fact[n-1], mod-2, mod) * pow(fact[i-n], mod-2, mod) % mod
    ret *= pow(25, i-n, mod)
    ret *= pow(26, k + n - i, mod)
    ans += ret
    ans %= mod
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys

MOD = 1000000007  # type: int

def solve(K: int, S: str):
    '''
    >>> solve(1, 'a')
    51
    '''
    N = len(S)
    mf = ModFactorial(MOD, N+K+1)
    ans = 0    
    for k in range(K+1):
        ans = (ans + mf.combination(k+N-1, k) * pow(25, k, MOD) % MOD * pow(26, K-k, MOD)) % MOD
    return ans

# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    K = int(next(tokens))  # type: int
    S = next(tokens)  # type: str
    print(solve(K, S))

def mod_range(mod, start, stop=None, step=1):    
    if stop == None:
        stop = start
        start = 0
    return map(lambda i: i % mod, range(start, stop, step))

def mod_inv(mod, n):
    '''
    >>> mod_inv(3, 2)
    2
    >>> mod_inv(1000000007, 2)
    500000004
    '''
    return pow(n, mod-2, mod)

def mod_permutation(mod, n, r):
    '''
    >>> mod_permutation(1000000007, 10, 2)
    90
    >>> mod_permutation(7, 10, 2)
    6
    '''
    m = 1
    for i in mod_range(mod, n-r+1, n+1):
        m = (m * i) % mod
    return m

def mod_factorial(mod, n):
    '''
    >>> mod_factorial(1000000007, 10)
    3628800
    >>> mod_factorial(7, 6)
    6
    '''
    return mod_permutation(mod, n, n)

def mod_combination(mod, n, r):
    '''
    >>> mod_combination(1000000007, 10, 2)
    45
    >>> mod_combination(7, 10, 2)
    3
    '''
    return mod_permutation(mod, n, r) * mod_inv(mod, mod_factorial(mod, r)) % mod

class ModFactorial:
    def __init__(self, mod, size=1):
        '''
        >>> ModFactorial(7, 7)
        Traceback (most recent call last):
        ...
        AssertionError
        '''
        assert mod > size
        self._mod = mod
        self._init_factorials(size)

    def _mod_range(self, start, stop=None, step=1):
        return mod_range(self._mod, start, stop, step)
    
    def _mod_inv(self, n):
        return mod_inv(self._mod, n)
    
    def _init_factorials(self, size):
        '''
        >>> mf1 = ModFactorial(1000000007)
        >>> mf2 = ModFactorial(1000000007, 10)
        >>> mf1.factorial(10) == mf2.factorial(10)
        True
        '''
        self._factorials = [1] * size        
        n = 1 # リストの参照は遅いので減らす
        for i, m in enumerate(self._mod_range(1, size), 1):
            n = (n * m) % self._mod
            self._factorials[i] = n
            
    def _append_factorials(self, n):
        for m in map(lambda i: i % self._mod, range(len(self._factorials), n+1)):
            self._factorials.append((self._factorials[-1] * m) % self._mod)

    def factorial(self, n):
        '''
        >>> ModFactorial(1000000007).factorial(10)
        3628800
        >>> ModFactorial(7).factorial(6)
        6
        >>> ModFactorial(7).factorial(7)
        Traceback (most recent call last):
        ...
        AssertionError
        '''
        assert n < self._mod
        if len(self._factorials) <= n:
            self._append_factorials(n)
        return self._factorials[n]

    def factorial_inv(self, n):
        '''
        >>> MOD = 1000000007
        >>> mf = ModFactorial(MOD)
        >>> mf.factorial_inv(10)
        283194722
        >>> mf.factorial_inv(10) * mf.factorial(10) % MOD
        1
        >>> MOD = 7
        >>> mf = ModFactorial(MOD)
        >>> mf.factorial_inv(6)
        6
        >>> mf.factorial_inv(6) * mf.factorial(6) % MOD
        1
        '''
        return self._mod_inv(self.factorial(n))

    def permutation(self, n, r):
        '''
        >>> ModFactorial(1000000007).permutation(10, 2)
        90
        '''
        return self.factorial(n) * self.factorial_inv(n-r) % self._mod

    def combination(self, n, r):
        '''
        >>> ModFactorial(1000000007).combination(10, 2)
        45
        '''
        return self.permutation(n, r) * self.factorial_inv(r) % self._mod

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    #test()
    main()

Submission status: Accepted

Solution code:
k = int(input())
s = input()
 
l = len(s)
mod = 10**9+7 #出力の制限
 
n = l+k
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル
for i in range( 2, n + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )
def cmb(n, r):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod
 

 
ans = 0
for i in range(l,l+k+1):
    ans = (ans+cmb(i-1,l-1)*pow(25,k-(l+k-i),mod)*pow(26,l+k-i,mod)) % mod
 
print(ans)

Submission status: Accepted

Solution code:
k = int(input())
s = input()
n = len(s)
mod = 10 ** 9 + 7

f = [1, 1]
f_inv = [1, 1]
inv = [0, 1]
 
for i in range(2, n+k+1):
    f.append((f[-1] * i ) % mod)
    inv.append((-inv[mod % i] * (mod // i) ) % mod)
    f_inv.append((f_inv[-1] * inv[-1]) % mod)

def comb(n, k):
    return f[n] * f_inv[k] * f_inv[n-k] % mod

ans = 0
for i in range(k+1):
    x = pow(25, i, mod) * pow(26, k-i, mod) * comb(n-1+i, n-1)
    ans += x
    ans %= mod

print(ans)

Submission status: Accepted

Solution code:
k = int(input())
s = input()
l = len(s)
MOD = 10 ** 9 + 7


def comb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n - r] % p


p = MOD
N = 10 ** 6 * 2 + 10 # N は必要分だけ用意する
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

# Sn の位置をx = l-1,l,..,l+k-1まで全て動かす
# pow(25,x-l-1,MOD)* x-1Cl-1 * pow(26,l+k-1-x,MOD) をかければOK
ans = 0
for x in range(l - 1, l + k):
    ans += pow(25, x - l + 1, MOD) * comb(x, l - 1, MOD) * pow(26, l + k - 1 - x, MOD)
    ans %= MOD
print(ans)
"""
# dp[i][j]:k+l の長さの文字列の中で、長さi で、sのj番目の文字列まじで含む文字列の個数とする
# dp[i][j] = dp[i-1][j-1] + dp[i-1][j] * 25 となる
# これだと10**12でTLEなので、まとめる
# 答えたいのは、dp[k+l][l]で初期化はdp[1][1] = 1 dp[1][0] = 25
# l までいったら遷移の仕方が変わって*26を続けるだけで良いようになる
dp = [[0] * (l + 1) for _ in range(k + l + 1)]
dp[0][0] = 1
for i in range(1, k + l + 1):
    for j in range(l + 1):
        if j == l:
            dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] * 26
        else:
            dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] * 25
        dp[i][j] %= MOD
print(dp[k + l][l])
"""

Submission status: Accepted

Solution code:
K = int(input())
S = input()
MOD = 10**9 + 7


def cmb(n, r, MOD):
    if (r < 0 or r > n):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % MOD


N = 3*10**6
g1 = [1, 1]  # 元テーブル
g2 = [1, 1]  # 逆元テーブル
inverse = [0, 1]  # 逆元テーブル計算用テーブル

for i in range(2, N + 1):
    g1.append((g1[-1] * i) % MOD)
    inverse.append((-inverse[MOD % i] * (MOD//i)) % MOD)
    g2.append((g2[-1] * inverse[-1]) % MOD)

ans = 0
for i in range(len(S), len(S)+K+1):
    ans += cmb(i-1, len(S)-1, MOD)*pow(25, i-len(S), MOD) * \
        pow(26, len(S)+K-i, MOD)
    ans %= MOD
print(ans)

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

mod = 10**9 + 7
k = int(input())
s = input()
n = len(s)

def make_tables(n, mod = 10 ** 9 + 7):
    fac = [1, 1] # 階乗テーブル
    finv = [1, 1] #逆元の階乗テーブル
    inv = [0, 1] #逆元テーブル

    for i in range(2, n + 1):
        fac.append((fac[-1] * i) % mod)
        inv.append((mod -inv[mod % i] * (mod // i)) % mod)
        finv.append((finv[-1] * inv[-1]) % mod)
    return fac, finv

def nCk(n, k, mod = 10 ** 9 + 7):
    k = min(k, n-k)
    return fac[n] * finv[k] * finv[n-k] % mod

##########################
fac, finv = make_tables(2*10**6 + 1)
ans = 0
for i in range(k + 1):
    temp = 1
    temp *= pow(26, i, mod)
    temp %= mod
    j = k - i
    temp *= pow(25, j, mod)
    temp %= mod
    temp *= nCk(n + j - 1, n - 1)
    ans += temp
    ans %= mod
print(ans % mod)