Problem:


Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap



Sample input:
xyz
4


Sample output:
aya

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def next_char_ascii_num(c, k):
    n = ord(c) + (k % 26)
    if n <= 122:
        return n
    else:
        return n % 123 + 97

s = input()
k = int(input())
d = []
l = len(s)

for i, x in enumerate(s):

    if k <= 0:
        l = i
        break

    else:
        if k >= 25 and l != 1:
            d.append(97)
            k -= (26 - (ord(x) - 97))
        else:
            v =[next_char_ascii_num(x, y) for y in range(k + 1)]
            min_index = v.index(min(v))
            d.append(v[min_index])
            k -= min_index


if k > 0:
    d[-1] = next_char_ascii_num(chr(d[-1]), k)
else:
    d += s[l:]

print("".join([chr(x) for x in d]))

Submission status: Time Limit Exceeded

Solution code:
def next_letter(target_string, character_position, last_K):
    """
    与えられた文字列のcharacter_position番目（ただし0からはじまる）の文字をnumber個進める
    """
    number = last_K % 26
    letter = target_string[character_position]
    letter_askii = ord(letter)
    next_letter = chr(letter_askii + number)
    result_string = target_string[:character_position] + next_letter + target_string[character_position+1:]
    return  result_string

target_string = input()
K = int(input())

#まずはaにできないところまで左からaにしていく
for i, letter in enumerate(target_string):
    if K == 0:
        break
    next_letter_num_to_a = (ord("z") - ord(letter) + 1) % 26
    if next_letter_num_to_a > K:
        continue
    else:
        target_string = target_string[:i] + "a" + target_string[i+1:]
        K -= next_letter_num_to_a

# 最後に最下位をすすめる
if K == 0:
    print (target_string)
else:
    last_character_pos = len(target_string) - 1
    target_string = next_letter(target_string, last_character_pos, K)
    print (target_string)

Submission status: Time Limit Exceeded

Solution code:
def next_letter(target_string, character_position, last_K):
    """
    与えられた文字列のcharacter_position番目（ただし0からはじまる）の文字をnumber個進める
    """
    number = last_K % 26
    letter = target_string[character_position]
    letter_askii = ord(letter)
    next_letter = chr(letter_askii + number)
    result_string = target_string[:character_position] + next_letter + target_string[character_position+1:]
    return  result_string
 
target_string = input()
K = int(input())
 
# print (target_string_list)
#まずはaにできないところまで左からaにしていく
for i, letter in enumerate(target_string):
    next_letter_num_to_a = (ord("z") - ord(letter) + 1) % 26
    if next_letter_num_to_a > K:
        continue
    else:
        target_string = target_string[:i] + "a" + target_string[i+1:]
        K -= next_letter_num_to_a
 
# 最後に最下位をすすめる
if K == 0:
    print (target_string)
else:
    last_character_pos = len(target_string) - 1
    target_string = next_letter(target_string, last_character_pos, K)
    print (target_string)

Submission status: Time Limit Exceeded

Solution code:
s = list(input())
K = int(input())

for i in range(len(s)):
    if s[i] == "a":
        pass
    elif 123 - ord(s[i]) <= K:
        K -= (123 - ord(s[i]))
        s[i] = 'a'

while K > 0:
    K -= 1
    if s[-1] == "z":
        s[-1] = "a"
    else:
        s[-1] = chr(ord(s[-1]) + 1)
print("".join(s))

Submission status: Time Limit Exceeded

Solution code:
s = raw_input()
K = input()

alpha = [chr(i) for i in range(97,97+26)]

for moji in range(len(s)):
	if alpha.index(s[moji]) != 0:
		if K >= 26-alpha.index(s[moji]):
			K = K - (26-alpha.index(s[moji]))
			s = s[:moji] + 'a' + s[moji+1:] 

if K>0:
	last_char = alpha[ alpha.index(s[-1]) + (K % 26) ]
	s = s[:-1] + last_char

print s

Submission status: Time Limit Exceeded

Solution code:
def next_letter(target_string, character_position, last_K):
    """
    与えられた文字列のcharacter_position番目（ただし0からはじまる）の文字をnumber個進める
    """
    number = last_K % 26
    letter = target_string[character_position]
    letter_askii = ord(letter)
    next_letter = chr(letter_askii + number)
    result_string = target_string[:character_position] + next_letter + target_string[character_position+1:]
    return  result_string

target_string = input()
K = int(input())

# print (target_string_list)
#まずはaにできないところまで左からaにしていく
for i, letter in enumerate(target_string):
    next_letter_num_to_a = (ord("z") - ord(letter) + 1) % 26
    if next_letter_num_to_a > K:
        continue
    else:
        target_string = target_string[:i] + "a" + target_string[i+1:]
        K -= next_letter_num_to_a

# 最後に最下位をすすめる
if K == 0:
    print (target_string)
else:
    last_character_pos = len(target_string) - 1
    target_string = next_letter(target_string, last_character_pos, K)
    print (target_string)

Submission status: Time Limit Exceeded

Solution code:
s = raw_input()
K = input()

alpha = [chr(i) for i in range(97,97+26)]

for moji in range(1, len(s)+1):
	if alpha.index(s[moji-1]) != 0:
		if K >= 26-alpha.index(s[moji-1]):
			K = K - (26-alpha.index(s[moji-1]))
			s = s[:moji-1] + 'a' + s[moji:] 

if K>0:
	last_char = alpha[ alpha.index(s[-1]) + (K % 26) ]
	s = s[:-1] + last_char

print s

Submission status: Time Limit Exceeded

Solution code:
def next_letter(target_string, character_position):
    """
    与えられた文字列のcharacter_position番目（ただし0からはじまる）の文字を1つ進める
    """
    letter = target_string[character_position]
    letter_askii = ord(letter)
    next_letter = chr(letter_askii + 1)

    if letter_askii == 122:
        next_letter = "a"

    result_string = target_string[:character_position] + next_letter + target_string[character_position+1:]
    return  result_string

target_string = input()
K = int(input())

# print (target_string_list)
#まずはaにできないところまで左からaにしていく
for i, letter in enumerate(target_string):
    next_letter_num_to_a = (ord("z") - ord(letter) + 1) % 26
    if next_letter_num_to_a > K:
        continue
    else:
        target_string = target_string[:i] + "a" + target_string[i+1:]
        K -= next_letter_num_to_a

# 最後に最下位をすすめる
if K == 0:
    print (target_string)
else:
    last_character_pos = len(target_string) - 1
    for i in range(K):
        target_string = next_letter(target_string, last_character_pos)
    print (target_string)

Submission status: Time Limit Exceeded

Solution code:
def f(s,K):
 if len(s)==1:
  K%=26
  if ord(s[0])+K<123:
   return chr(ord(s[0])+K)
  else:
   return chr(ord(s[0])+K-26)
 res=0
 for i in range(len(s)):
  if s[i]=="a":
   continue
  if K>=123-ord(s[i]):
   res+=1
   K-=123-ord(s[i])
  else:
   break
 str=""
 for i in range(res):
  str+="a"
 if res==0:
  return s[0]+f(s[1:],K)
 return str+f(s[res:],K)
ss=input()
KK=int(input())
print(f(ss,KK))

Submission status: Time Limit Exceeded

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

def solve(s, k, i):
    if i >= len(s):
        # print "over"
        return s
    if i == len(s)-1:
        # print "equal"
        t = ord(s[i])+k
        if t > ord("z"):
            # n = (ord("z") - ord("a") + 1)/(t - ord("z"))
            # t = t - (ord("z")-ord("a"))*n
            while t > ord("z"):
                t -= (ord("z") - ord("a") + 1)
        s = s[:i] + chr(t)
        # print s, k
    elif ord(s[i]) + k > ord("z"):
        # print "carry"
        k = k - ord("z") + ord(s[i]) -1
        s = s[:i] + "a" + s[i+1:]        
        # print s,k
    return solve(s,k,i+1)
    
print solve(s,k,0)

Submission status: Time Limit Exceeded

Solution code:
moji=input()

num=int(input())
re = "abcdefghijklmnopqrstuvwxyz"
a = [(re.index(j)+1)*(10**(len(moji)-i-1)) if j!="a" else 0 for i,j in enumerate(moji)]
kk = [26-re.index(j[0]) for i,j in enumerate(zip(moji,a))]
"""
for i,j in enumerate(kk):
    if j<num:
        n_moji.append("a")
        num-=j
    else:
        n_moji.append(moji[i])
"""
def k(x,y):
    global num
    #global moji
    if y < num:
        num-=y
        return "a"
    else:
        return moji[x]


n_moji = [k(i,j) for i,j in enumerate(kk)]
n_moji.pop()
n_moji.append(re[re.index(moji[-1])+num%26])
print("".join(n_moji))

Submission status: Time Limit Exceeded

Solution code:
def f(s,K):
 if len(s)==1:
  if ord(s[0])+K<123:
   return chr(ord(s[0])+K)
  else:
   return chr((((ord(s[0])+K)-97)%26)+97)
 res=0
 for i in range(len(s)):
  if s[i]=="a":
   continue
  if K>=123-ord(s[i]):
   res+=1
   K-=123-ord(s[i])
  else:
   break
 str=""
 for i in range(res):
  str+="a"
 if res==0:
  return s[0]+f(s[1:],K)
 return str+f(s[res:],K)
ss=input()
KK=int(input())
print(f(ss,KK))

Submission status: Time Limit Exceeded

Solution code:
moji=input()
num=int(input())
re = "abcdefghijklmnopqrstuvwxyz"
a = [(re.index(j)+1)*(10**(len(moji)-i-1)) if j!="a" else 0 for i,j in enumerate(moji)]
kk = [(26-re.index(j[0]),(26-re.index(j[0]))*(10 ** (len(moji)-i-1)),j[1]) for i,j in enumerate(zip(moji,a))]
n_moji=[]

for i,j in enumerate(kk):
    if j[0]<num:
        n_moji.append("a")
        num-=j[0]
    else:
        n_moji.append(moji[i])
n_moji.pop()
n_moji.append(re[re.index(moji[-1])+num%26])
print("".join(n_moji))

Submission status: Time Limit Exceeded

Solution code:

#aまでいけそうなら動かす。駄目そうならその項は終わり
import sys


def move(s, k):
    if len(s) == 1:
        return chr(97+(ord(s) + k - 97)%26)
    if s[0] == 'a' or 123-ord(s[0]) > k:
        return s[0] + move(s[1:], k)
    else:
        return 'a' + move(s[1:], k-(123-ord(s[0])))


s = input()
K = int(input())
sys.setrecursionlimit(20000)
print(move(s,K))

Submission status: Time Limit Exceeded

Solution code:
s = input()
s += " "
K = int(input())
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
k = 0
while K != k:
	k = K
	for i in range(len(s) - 1):
		gap = (26 - alphabet.index(s[i])) % 26
		if K >= gap:
			K -= gap
			s = s[:i] + "a" + s[i+1:]

s = s[:-1]
if K:
	n = alphabet.index(s[-1])
	n += K
	n %= 26
	s = s[:-1] + alphabet[n]


print(s)

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
from heapq import heappop, heappush
from collections import defaultdict
from collections import Counter
from collections import deque
from itertools import permutations
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())
S = input()
K = int(input())

ans = []
for i, c in enumerate(S):
    if c == 'a':
        ans.append(c)
        continue
    num = ord('z') - ord(c) + 1
    if K >= num:
        K -= num
        ans.append('a')
    else:
        ans.append(c)
if K > 0:
    ans[-1] = chr((ord(ans[-1]) - ord('a') + K % 26) % 26 + ord('a'))
print("".join(ans))

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
ls = list("abcdefghijklmnopqrstuvwxyz")
ls.sort(reverse=True)
ls = ["a"] + ls[:-1]
for i in range(len(s)):
    if i != len(s)-1:
        if k >= ls.index(s[i]):
            k -= ls.index(s[i])
            s[i] = "a"
        else:
            continue
    else:
        k %= 26
        s[-1] = ls[(ls.index(s[-1])-k)%26]
print("".join(s))

Submission status: Accepted

Solution code:
s=input()
k=int(input())
num=[(123-ord(s[i]))%26 for i in range(len(s))]
ans=""
for i in range(len(s)-1):
    if num[i]<=k:
        ans+="a"
        k-=num[i]
    else:
        ans+=s[i]
k%=26
if num[-1]<=k:
    ans+=chr(97+k-num[-1])
else:
    ans+=chr(ord(s[-1])+k)
print(ans)

Submission status: Accepted

Solution code:
s = input()
k = int(input())
v = list(s)
n = len(s)
a = [0 for i in range(n)]

for i in range(n):
  a[i] = (123 - ord(s[i]))%26
  if k == 0:
    break
  if k >= a[i]:
    v[i] = 'a'
    k -= a[i]

if k > 0:
  k %= 26
  v[n-1] = chr(ord(v[n-1])+k)
print (''.join(v))

Submission status: Accepted

Solution code:
import sys, math
from itertools import accumulate
sys.setrecursionlimit(10**9)

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]


def main():
    s, K = input(), ii()
    l = list(map(lambda c: (ord('z')-ord(c)+1)%26, s))

    acc = 0
    t = ['']*len(s)
    for i in range(len(s)):
        if acc + l[i] <= K:
            acc += l[i]
            t[i] = 'a'
        else:
            t[i] = s[i]

    if i == len(s)-1 and K-acc > 0:
        t[i] = chr((ord(t[i])-ord('a')+K-acc)%26+ord('a'))

    print(''.join(t))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline


def read():
    s = input().strip()
    K = int(input().strip())
    return s, K


def solve(s, K):
    ans = []
    for a in s:
        c = (ord("z") - ord(a) + 1) % 26
        if c <= K:
            K -= c
            ans.append("a")
        else:
            ans.append(a)
    if K > 0:
        c = (ord(ans[-1]) - ord("a") + K) % 26
        ans[-1] = chr(c + ord("a"))
    return "".join(ans)


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("%s" % str(outputs))

Submission status: Accepted

Solution code:
S=input()
K=int(input())
lenS=len(S)
for i in range(lenS-1):
    ordS_i=ord(S[i])
    if (ord("a")-ordS_i)%26<=K:
        K-=(ord("a")-ordS_i)%26
        S=S[:i]+"a"+S[i+1:]
ordS_i=ord(S[lenS-1])
moda=(ordS_i-ord("a")+K)%26
S=S[:lenS-1]+chr(ord("a")+moda)
print(S)

Submission status: Accepted

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

for i in range(len(s)):
    a = 26-(ord(s[i])-97)
    # print(ord(s[i]))
    # print(a)
    if k >= a and a != 26:
        k -= a
        s[i] = "a"
# print(k)
s[-1] = chr(ord(s[-1]) + k % 26)
# print(ord(s[-1]))
print("".join(s))

Submission status: Accepted

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

for i in range(len(s)):
    if s[i] != "a":
        req = ord("z") - ord(s[i]) + 1

        if req <= k:
            k -= req
            s = s[:i] + "a" + s[i+1:]

if k > 0:
    s = s[:-1] + chr(ord(s[-1]) + k%26)

print(s)

Submission status: Accepted

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

ans = ""
for si in s:
  if si == "a":
    ans += "a"
    continue
  num = ord("z") - ord(si) + 1
  if num <= k:
    ans += "a"
    k -= num
  else:
    ans += si

if k > 0:
  num = k % 26
  if ord(ans[-1]) + num <= ord("z"):
    new_c = chr(ord(ans[-1]) + num)
  else:
    num -= ord("z") - ord(ans[-1])
    new_c = chr(ord("a") - 1 + num)
  print(ans[:-1] + new_c)
else:
  print(ans)

Submission status: Accepted

Solution code:

def resolve():
    def decode(x):
        return ord(x) - 97

    def encode(x):
        return chr(x + 97)

    S = list(map(decode, input()))
    K = int(input())

    for i in range(len(S) - 1):
        if S[i] == 0:
            continue
        if 26 - S[i] <= K:
            K -= 26 - S[i]
            S[i] = 0

    S[-1] = (S[-1] + K) % 26
    ans = map(encode, S)
    print("".join(ans))


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:

def resolve():
    S = input()
    K = int(input())

    ans = []
    for s in S:
        diff = ord(s) - ord("a")
        if diff == 0:
            ans.append("a")
            continue
        elif 26 - diff <= K:
            ans.append("a")
            K -= 26 - diff
        else:
            ans.append(s)

    K %= 26
    d = (K + ord(ans[-1]) - ord('a')) % 26
    ans[-1] = chr(d + ord('a'))

    print("".join(ans))


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
import sys
from sys import exit
from collections import deque
from copy import deepcopy
from bisect import bisect_left, bisect_right, insort_left, insort_right
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod=MOD):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
    def list(self):
        l = []
        for k in self:
            l.extend([k]*self[k])
        return l
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]
def pf(x,mode='counter'):
    C = counter()
    p = 2
    while x>1:
        k = 0
        while x%p==0:
            x //= p
            k += 1
        if k>0:
            C.add(p,k)
        p = p+2-(p==2) if p*p<x else x
    if mode=='counter':
        return C
    S = set([1])
    for k in C:
        T = deepcopy(S)
        for x in T:
            for i in range(1,C[k]+1):
                S.add(x*(k**i))
    if mode=='set':
        return S
    if mode=='list':
        return sorted(list(S))

s=input()
N=len(s)
K=intput()
ans=[]
for i in range(N-1):
    if (26-ston(s[i]))%26<=K:
        ans.append('a')
        K-=(26-ston(s[i]))%26
    else:
        ans.append(s[i])
ans.append(ntos((ston(s[N-1])+K)%26))
lprint(ans,'')

Submission status: Accepted

Solution code:
S = input()
K = int(input())

oz = ord("z")

ans = ""

for s in S[:-1]:
    if s != "a" and oz+1-ord(s) <= K:
        K -= oz+1-ord(s)
        ans += "a"
    else:
        ans += s

ans += chr(((ord(S[-1])-ord("a")+K)%26)+ord("a"))

print(ans)

Submission status: Accepted

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

for i, c in enumerate(s):
    t = (ord("z") - ord(c) + 1) % 26
    if k >= t:
        s[i] = "a"
        k -= t

t = k % 26
s[-1] = chr(ord(s[-1]) + t)

print("".join(s))

Submission status: Accepted

Solution code:
S = input()
S = list(S)

def func(c) -> int:
    t = 26 - (ord(c) - ord('a'))
    t %= 26
    return t

L = [func(c) for c in S]
#print(L)
K = int(input())
for i in range(len(L)):
    if(L[i] <= K):
        K -= L[i]
        L[i] = 0
    else:
        continue
#print(L)
if(K > 0):
    #L[-1]
    K %= 26
    L[-1] -= K
    if(L[-1] < 0):
        L[-1] += 26

def gunc(c):
    t = 26 - c
    t %= 26
    return chr(t+97)
ans = [gunc(c) for c in L]
st = ''
for c in ans:
    st += c
print(st)

Submission status: Accepted

Solution code:
def main():
    S = list(input())
    K = int(input())
    L = len(S)
    for i in range(L):
        if S[i] == 'a':
            continue
        if ord('z') - ord(S[i]) + 1 <= K:
            K -= ord('z') - ord(S[i]) + 1
            S[i] = 'a'

    if K > 0:
        S[-1] = chr(ord(S[-1]) + K % 26)

    print(''.join(S))




if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
#print(ord("z"))
for i in range(len(s)):
  if s[i] != 'a' and 123 - ord(s[i]) <= k:
    k -= (123 - ord(s[i]))
    s[i] = "a"
    #print(k)
#print(s, k)
k %= 26
if ord(s[-1]) + k > 122:
  s[-1] = chr(ord(s[-1]) + k - 26)
else:
  s[-1] = chr(ord(s[-1]) + k)
ans = ""
for i in s:
  ans += i
print(ans)

Submission status: Accepted

Solution code:
import sys
# sys.setrecursionlimit(100000)


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


def input_int():
    return int(input())


def input_int_list():
    return [int(i) for i in input().split()]


def main():
    S = list(input())
    k = input_int()

    # 方針: 左の文字から貪欲に a を作る
    #       余ったk は一番右の文字の操作につかう
    for i in range(len(S)):
        c = ord(S[i])
        if c == ord("a"):
            continue
        dif = ord("z") - c + 1
        if dif <= k:
            S[i] = "a"
            k -= dif
    # 余ったkを一番右の文字の操作に使う
    S[-1] = chr(ord("a") + ((ord(S[-1]) - ord("a")) + (k % 26)))
    print("".join(S))
    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s = list(input())
K = int(input())
zp1 = 1+ord('z')
for i in range(len(s)):
    si = s[i]
    cost = (zp1-ord(si))%26
    if cost <= K:
        K -= cost
        s[i] = 'a'
s[-1] = chr(ord('a') + (K + ord(s[-1]) - ord('a')) % 26)
print(''.join(s))

Submission status: Accepted

Solution code:
def main():
    S = input()
    K = int(input())
    ans = ['' for _ in range(len(S))]
    for i in range(len(S)):
        d = ord(S[i]) - ord('a')
        shift = (26 - d) % 26
        if K - shift >= 0:
            ans[i] = 'a'
            K -= shift
        else:
            ans[i] = S[i]
    if K > 0:
        K %= 26
        d = (K + ord(ans[-1]) - ord('a')) % 26
        ans[-1] = chr(d + ord('a'))
    print(''.join(ans))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
class common_function():
    """
        1. よく使いそうで予め用意しておいた変数をまとめた
        2. よく使いそうな関数群をまとめた
    """
    def __init__(self):
        """
            1. 英字の一覧をリストに格納しておいた変数
        """
        self.sletter = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
        self.bletter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']


def main():
    common = common_function()
    s = list(input())
    K = int(input())
    t = [0]
    for i in range(len(common.sletter)-1, 0, -1):
        t.append(i)

    u = []
    for i in range(len(s)):
        u.append(t[common.sletter.index(s[i])])
    
    ans = ''
    for i in range(len(s)-1):
        if u[i] <= K:
            ans += 'a'
            K -= u[i]
        else:
            ans += s[i]
    K = K%26
    if u[len(s)-1] <= K:
        K -= u[len(s)-1]
        ans += common.sletter[K]
    else:
        ans += common.sletter[common.sletter.index(s[len(s)-1])+K]
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s = list(input())
n = len(s)
k = int(input())

for i in range(n):
    if k > 0 and i == n-1:
        x = ord(s[i])-ord("a")
        s[i] = chr((k+x)%26+ord("a"))
        break
    if s[i] == "a":
        continue
    x = ord(s[i])-ord("a")

    if k >= 26-x:
        s[i] = "a"
        k -= 26-x
print(*s,sep="")

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
for i in range(len(s)):
  dp = 26-ord(s[i])+97
  if k >= dp and s[i] != "a":
    k-=dp
    s[i] = "a"
    if k == 0:
      break
else:
  s[-1] = chr((ord(s[-1])-97+k)%26+97)
print(*s,sep="")

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
num = len(s)

for i in range(num):
    a = 122-ord(s[i])+1
    if a <= k and s[i] != 'a':
        k -= a
        s[i] = 'a'
if k > 0:
    s[-1] = chr(ord(s[-1])+k%26)
print(*s, sep='')

Submission status: Accepted

Solution code:
alpha=[chr(ord('a') + i) for i in range(26)]
a=list(input())
N=int(input())
for i in range(len(a)):
   s=26-alpha.index(a[i])
   if s<=N and s!=26:
      a[i]="a"
      N-=s
s=alpha.index(a[-1])
s=(s+N)%26
a[-1]=alpha[s]
print(*a,sep="")

Submission status: Accepted

Solution code:
s = list(input())
K = int(input())
l = len(s)
for i in range(l-1):
    x = (ord('a')-ord(s[i])) % 26
    if x <= K:
        K -= x
        s[i] = 'a'
s[l-1] = chr(ord('a') + (ord(s[-1])-ord('a')+K) % 26)
print(''.join(s))

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
n = len(s)
for i in range(n):
    if k <= 0 or s[i] == 'a':
        continue
    if 123 - ord(s[i]) <= k:
        k -= 123 - ord(s[i])
        s[i] = 'a'
# print(k)
# print(s)
k %= 26
# print(ord(s[-1])+k)
if ord(s[-1])+k > 122:
    s[-1] = chr(97+(122-ord(s[-1])+k))
else:
    s[-1] = chr(ord(s[-1])+k)
# print(k)
print(*s, sep='')

Submission status: Accepted

Solution code:
s = list(input())
K = int(input())
ans = []
for c in s:
    cnt = ord('z') - ord(c) + 1
    if c == 'a':
        ans.append('a')
    elif K >= cnt:
        K -= cnt
        ans.append('a')
    else:
        ans.append(c)
K %= 26
if 122 < ord(ans[-1]) + K:
    ans[-1] = chr(ord(ans[-1]) + K - 26)
else:
    ans[-1] = chr(ord(ans[-1]) + K)
print(*ans,sep='')

Submission status: Accepted

Solution code:
from string import ascii_lowercase
s = input()
k = int(input())

def main(s, k):
    alp = ascii_lowercase
    num = {char: i for i, char in enumerate(alp)}

    ns = [num[char] for char in s]

    for i in range(len(ns)):
        v = ns[i]
        if v != 0 and 26 - v <= k:
            ns[i] = 0
            k -= 26 - v

    ns[-1] = (ns[-1] + k) % 26

    return ''.join(alp[n] for n in ns)
print(main(s, k))

Submission status: Accepted

Solution code:

list = {'a':0,'b':25,'c':24,'d':23,'e':22,'f':21,'g':20,'h':19,
         'i': 18,'j':17,'k':16,'l':15,'m':14,'n':13,'o':12,'p':11,
         'q': 10,"r":9,'s':8,'t':7,'u':6,'v':5,'w':4,'x':3,'y':2,'z':1}
list2 = {0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g',7:'h',
         8:'i',9:'j',10:'k',11:'l',12:'m',13:'n',14:'o',15:'p',
         16:'q',17:"r",18:'s',19:'t',20:'u',21:'v',22:'w',23:'x',24:'y',25:'z'}
list3 = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,
         'i': 8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,
         'q': 16,"r":17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}
s = input()

K = int(input())

for i in range(len(s)):
    num = list[s[i]]
    if num <=K:
        s = s[:i] + 'a' + s[i+1:]
        K -= num

if K >0:
    print(s[:-1]+list2[(list3[s[-1]]+K)%26])
else:
    print(s)

Submission status: Accepted

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

ans = []
rem = k
for si in s[:-1]:
    if si == 'a':
        to_a = 0
    else:
        to_a = ord('z') - ord(si) + 1

    if to_a <= rem:
        rem -= to_a
        ans.append('a')
    else:
        ans.append(si)
        # next_s = chr(ord(si) + rem)
        # ans.append(next_s)
        # rem = 0


last_s_ord = (ord(s[-1]) + rem - ord('a'))%26
last_s = chr(ord('a') + last_s_ord)
ans.append(last_s)
ans = ''.join(ans)
print(ans)

Submission status: Accepted

Solution code:
import string
abc = string.ascii_lowercase
s = list(input())
K = int(input())
index = 0
while K > 0:
    if index == len(s) - 1:
        s[index] = abc[(abc.index(s[index]) + K) % 26]
        break
    tmp = 26 - abc.index(s[index])
    if tmp == 26:
        index += 1
        continue
    if K >= tmp:
        s[index] = 'a'
        index += 1
        K -= tmp
    else:
        index += 1

for i in s:
    print(i, end='')

Submission status: Accepted

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

for i, c in enumerate(s):
    t = (ord("z") - ord(c) + 1) % 26
    if k >= t:
        s[i] = "a"
        k -= t

t = k % 26
s[-1] = chr(ord(s[-1]) + t)

print("".join(s))

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
def main():
    s = input()
    k = int(input())
    r = ""
    for se in s:
        if se == 'a':
            r += 'a'
        else:
            if 123 - ord(se) <= k:
                r += 'a'
                k -= (123 - ord(se))
            else:
                r += se
    if k:
        k = k % 26
        lastc = chr(k + ord(r[-1]))
        r = r[:-1] + lastc
    print(r)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
from itertools import accumulate
from bisect import bisect
def main():
    s = input()
    k = int(input())
    s2 = []
    s2a = s2.append
    for se in s:
        if ord(se) - 97:
            s2a(123 - ord(se))
        else:
            s2a(0)
    s2_ac = tuple(accumulate(s2))
    lens = len(s)
    if s2_ac[-1] < k:
        k -= s2_ac[-1]
        k = k % 26
        r = 'a' * (lens - 1) + chr(97 + k)
        print(r)
    elif s2_ac[-1] == k:
        r = 'a' * lens
        print(r)
    else:
        pos = bisect(s2_ac, k)
        if pos == 0:
            r = chr(k + ord(s[0])) + s[1:]
            print(r)
        elif s2_ac[pos-1] == k:
            r = 'a' * pos + s[pos:]
            print(r)
        else:
            r = 'a' * pos
            k -= s2_ac[pos-1]
            for i1 in range(pos, len(s)):
                if s2[i1] <= k:
                    r += 'a'
                    k -= s2[i1]
                else:
                    r += s[i1]
            if k:
                lastc = chr(ord(r[-1]) + k)
                r = r[:-1] + lastc
            print(r)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s=input()
k=int(input())
n=len(s)
num=[0]*n
for i in range(n):
    if s[i]!="a":
        num[i]=123-ord(s[i])
if sum(num)>=k:
    ans=""
    for i in range(n-1):
        if k>=num[i]:
            k-=num[i]
            ans+="a"
        else:
            ans+=s[i]
    if k>=num[-1]:
        ans+="a"
    else:
        ans+=chr(97+((ord(s[-1])-97+k)%26))
else:
    k-=sum(num)
    ans="a"*(n-1)
    ans+=chr(97+(k%26))
print(ans)

Submission status: Accepted

Solution code:
s = list(input())
n = len(s)
k = int(input())
alphabet = [chr(i) for i in range(97, 97+26)]
al_d = {}
for i in range(26):
    al_d[alphabet[i]] = i
for i in range(n):
    tobe_a = 26 - al_d[s[i]]
    if tobe_a <= k:
        tobe_a %= 26
        k -= tobe_a
        s[i] = 'a'
remain = k % 26
s[-1] = alphabet[al_d[s[-1]]+remain]
print(''.join(s))
# あー！最後にするんじゃなくてaでまとめられる場所があるならそうした方がいい？
# ただそれがあるならそれより前にaにしてるはず

Submission status: Accepted

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

L = []
for i in range(len(s)):
    L.append((ord("z")-ord(s[i])+1))

ans = ""
i = 0
while i < len(s):
    if s[i] == "a":
        ans +="a"
        i +=1
    elif k-L[i] >= 0:
        ans +="a"
        k -=L[i]
        i +=1
    else:
        ans +=s[i]
        i +=1
k = k%26
ans = ans[:-1] + chr(ord(ans[-1]) + k)
print(ans)

Submission status: Accepted

Solution code:
s=[s for s in input()]
k=int(input())
for i,j in enumerate(s):
  if j=='a':continue
  if ord('z')-ord(j)+1<=k:
    s[i]='a'
    k-=ord('z')-ord(j)+1
  if k==0:break
if k>0:s[-1]=chr(k%26+ord(s[-1]))
print(''.join(s))