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: Accepted

Solution code:
#!usr/bin/env python3
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.buffer.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():
    s = input()
    ans = []
    k = I()
    for i,si in enumerate(s):
        if si == "a":
            ans.append(si)
            continue
        j = (ord("a")-ord(si))%26
        if j <= k:
            k -= j
            ans.append("a")
        else:
            ans.append(si)
    k %= 26
    ans[-1] = chr(ord(ans[-1])+k)
    print(*ans,sep="")
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
S=list(input())
K=int(input())
N=len(S)

for i in range(N):
    if S[i]=="a":
        continue
    sa=ord("z")-ord(S[i])+1
    if sa<=K:
        K-=sa
        S[i]="a"

if K!=0:
    K%=26
    S[i]=chr(ord(S[i])+K)

print("".join(S))

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


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


def main():
    S = input()
    K = int(input())
    nums = []
    a = ord("a")
    for s in S:
        nums.append(ord(s) - a)

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

    if K > 0:
        nums[-1] = (nums[-1] + K) % 26

    ans = ""
    for n in nums:
        ans += chr(n + a)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=1
input_method=input_methods[using_method]

IN=lambda : map(int, input().split())
mod=1000000007

#+++++

def icc(c):
	ret=(ord('z') - ord(c) + 1)
	return ret
	
def nn(c,v):
	ret=chr(ord(c)+v)
	return ret

def main():
	s=input()
	n = int(input())
	#b , c = IN()
	#s = input()
	ret = []
	for c in s:
		#print(c,icc(c),n)
		if c != 'a' and icc(c) <= n:
			ret.append('a')
			n-=icc(c)
		else:
			ret.append(c)
	
	n%=26
	if icc(ret[-1]) <= n:
		n-=icc(ret[-1])
		ret[-1]='a'
	ret[-1]=nn(ret[-1], n)
	#pa(ret)
	return ''.join(ret)
	
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

Solution code:
s = input()
k = int(input())
loop = ord('z') + 1
remaining = k
ans = []
for c in s:
    if c == 'a':
        ans.append(c)
        continue
    r = loop - ord(c)
    if r <= remaining:
        ans.append('a')
        remaining -= r
    else:
        ans.append(c)
if remaining > 0:
    remaining %= 26
    ans[-1] = chr(ord(ans[-1]) + remaining)
print(''.join(ans))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue
from decimal import *


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [input() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [int(input()) for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def divisor(n):
        res = []
        i = 1
        for i in range(1, int(n ** 0.5) + 1):
            if n % i == 0:
                res.append(i)
                if i != n // i:
                    res.append(n // i)
        return res

    @staticmethod
    def round_up(a, b):
        return -(-a // b)

    @staticmethod
    def is_prime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True


def pop_count(x):
    x = x - ((x >> 1) & 0x5555555555555555)
    x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
    x = x + (x >> 8)
    x = x + (x >> 16)
    x = x + (x >> 32)
    return x & 0x0000007f


MOD = int(1e09) + 7
INF = int(1e15)


def solve():
    S = list(Scanner.string())
    K = Scanner.int()
    i = 0
    while i < len(S):
        c = S[i]
        n = ord(c) - ord('a')
        if n > 0 and 26 - n <= K:
            c = 'a'
            K -= 26 - n
            S[i] = c
        i += 1
    if K > 0:
        c = S[-1]
        for _ in range(K % 26):
            c = chr(ord(c) + 1)
            if c == chr(ord('z') + 1):
                c = 'a'
        S[-1] = c
    print(''.join(S))


def main():
    # sys.stdin = open("sample.txt")
    solve()


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

s = list(input())
k = int(input())
for i in range(len(s)):
    num = (ord('z') - ord(s[i]) + 1) % 26
    if num <= k:
        k -= num
        s[i] = 'a'
s[-1] = chr((ord(s[-1]) - ord('a') + k) % 26 + ord('a'))
print(*s, sep='')

Submission status: Accepted

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

for i in range(len(s)):
    if s[i] == 'a':
        continue
    n = ord('z') - ord(s[i]) + 1
    if n <= K:
        K -= n
        s[i] = 'a'

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

print(''.join(s))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
s=input()
K=int(input())

ans=[]
#122
for item in s[:len(s)-1]:
    cost=(123-ord(item))
    if item=="a":
        ans.append(item)
        continue
    if K>=cost:
        K-=cost
        ans.append("a")
    else:
        ans.append(item)

K%=26
last=ord(s[-1])
if last+K>122:
    ans.append(chr(last+K-26))
else:
    ans.append(chr(last+K))

print("".join(ans))

Submission status: Accepted

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

S = [ord(i)-97 for i in s]

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

if last > 0:
    S[-1] += last
    S[-1] %= 26

S = [chr(i+97) for i in S]
print(''.join(S))

Submission status: Accepted

Solution code:
s = [ord(x) - ord("a") for x in input()]
k = int(input())

for i, r in enumerate(s):
    if r == 0:
        pass
    elif 26 - r <= k:
        k -= 26-r
        s[i] = 0

if k > 0:
    k %= 26
    s[-1] += k

ans = ""
for r in s:
    ans += chr(ord("a") + r)

print(ans)

Submission status: Accepted

Solution code:
s = input()
k = int(input())
result = ""
i = 0
#a:97, z:122
while i < len(s)-1:
    s_i = ord(s[i])
    if s[i]=="a":
        result = result+"a"
    elif 123-s_i <= k:
        result = result+"a"
        k -= 123-s_i
    else:
        result = result+s[i]
    i += 1
if k>0:
    result = result + chr((ord(s[i])-97+k)%26+97)
else:
    result = result + s[i]

print(result)

Submission status: Accepted

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

S = list(s)

import string
A = [chr(i) for i in range(ord("a"), ord("z")+1)]
B = {}
for i in range(26):
    B[A[i]] = i

for i in range(n):
    if S[i] != "a" and 26 - B[S[i]] <= k:
        k -= 26 - B[S[i]]
        S[i] = "a"
        
# print(k)
if k > 0:
    S[-1] = A[(B[S[-1]] + k) % 26]

# print(S)

print("".join(S))

Submission status: Accepted

Solution code:
s = [ord(alph)-97 for alph in input()]
K = int(input())
i = 0
while K > 0 and i < len(s)-1:
    if s[i] != 0 and 26-s[i] <= K:
        K -= 26-s[i]
        s[i] = 0
    else:
        i += 1
s[-1] = (s[-1]+K)%26 
print(*[chr(x+97) for x in s], sep = '')

Submission status: Accepted

Solution code:
s = input()
n = len(s)
c = [ord(s[i]) for i in range(n)]
k = int(input())
ind = 0
while k > 0:
    if ind == n:
        break
    if c[ind] == 97:
        ind += 1
        continue
    elif 123 - c[ind] <= k:
        k -= 123-c[ind]
        c[ind] = 97
        ind += 1
    elif 123 - c[ind] > k:
        ind += 1
        continue

if k > 0:
    k %= 26
    c[-1] += k
    if c[-1] >= 123:
        c[-1] = 97 + (123-c[-1])

print(''.join([chr(c[i]) for i in range(n)]))

Submission status: Accepted

Solution code:
#n = int(input())
#n,k = map(int,input().split())
#x = list(map(int,input().split()))


def main():
    S = list(input())
    K = int(input())

    li = list("abcdefghijklmnopqrstuvwxyz")
    dic = {}
    for i,j in enumerate(li):
        dic[j] = 26-i
    dic["a"] = 0

    for i in range(len(S)):
        if dic[S[i]] <= K:
            K -= dic[S[i]]
            S[i] = "a"
    if K>0:
        num = (dic[S[-1]]-26)*(-1)
        S[-1] = li[(num+K)%26]

    for i in range(len(S)):
        print(S[i],end="")
    print()


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    word = list(input())
    operation = int(input())
    cost = {}
    for i in range(26):
        cost[chr(ord("a") + i)] = ord("z") - ord("a") - i + 1
    for i in range(len(word)):
        if cost[word[i]] <= operation and word[i] != "a":
            operation -= cost[word[i]]
            word[i] = "a"
        else:
            continue
    if 0 < operation:
        word[-1] = chr((ord(word[-1]) - ord("a") + operation % 26) % 26 + ord("a"))
    print("".join(word))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
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 S(): return input().rstrip()
def LS(): return S().split()
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

#solve
def solve():
    s = S()
    k = II()
    ans = []
    for si in s[:-1]:
        x = (ord("a") - ord(si)) % 26
        if x <= k:
            k -= x
            ans.append("a")
        else:
            ans.append(si)
    ans.append(chr(ord("a") + (k - (ord("a") - ord(s[-1])) % 26) % 26))
    print("".join(ans))
    return


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

Submission status: Accepted

Solution code:
def c2a(c):
    return (26 - ord(c) + ord("a")) % 26


s = input()
k = int(input())
l = len(s)
ans = ""
for i, e in enumerate(s, 1):
    if i == l:
        code = (ord(e) - ord("a") + k) % 26 + ord("a")
        c = chr(code)
    else:
        cnt = c2a(e)
        if cnt <= k:
            c = "a"
            k -= cnt
        else:
            c = e

    ans += c

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
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

goal = ord("z") + 1 
s = input()
k = int(input())
n = len(s)
ans = [0] * n
for i,si in enumerate(s):
  if si == "a":ans[i] = "a"
  elif goal - ord(si) <= k:
    k -= goal - ord(si)
    ans[i] = "a"
  else:
    ans[i] = si
m = k % 26
ans[-1] = chr((ord(ans[-1]) - ord("a") + m)%26 + ord("a"))
print(*ans,sep="")

Submission status: Accepted

Solution code:
S = list(input())
L = len(S)
K = int(input())
idx = 0
while K > 0:
    # aまでの必要な回数
    if S[idx] == "a" and idx < L-1:
        idx += 1
        continue
        
    k = 123 - ord(S[idx])
    if k > K:
        if idx < L-1:
            # aまで操作できないのに、操作すると辞書順でより後ろの文字列になってしまうので、次の文字へ
            idx += 1
        else:
            # 一番後ろの場合
            t = chr(ord(S[idx])+(K%26))
            S[idx] = t
            K = 0
    else:
        K -= k
        S[idx] = "a"
        if idx < L-1:
            idx += 1

print("".join(S))

Submission status: Accepted

Solution code:
s = input()
k = int(input())
slen = len(s)
new_s = ""

for i in range(slen):
  val = (ord("z") + 1 - ord(s[i])) % 26
  if k >= val:
    k -= val
    new_s += "a"
  else:
    new_s += s[i]
    
if k > 0:
  tmp_val = ord(new_s[slen-1]) + k % 26
  if tmp_val > ord("z"):
    tmp_val -= 26
  new_s = new_s[:-1] + chr(tmp_val)

print(new_s)

Submission status: Accepted

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

alp = list('abcdefghijklmnopqrstuvwxyz')
s2a = {alp[i]: 26-i for i in range(26)}
s2a['a'] = 0

for i in range(len(S)):
    s = S[i]
    if s2a[s] <= k:
        k -= s2a[s]
        S[i] = 'a'

k %= 26
idx = alp.index(S[-1])
S[-1] = alp[k+idx]

print(*S, sep='')

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
for i in range(len(s)):
  if ord("z")<ord(s[i])+k and s[i]!="a":
    k =k-(ord("z")-ord(s[i])+1)
    s[i]="a"
  if i==len(s)-1 and 0<k:
    k=k%26
    s[i]=chr(ord(s[i])+k)
print("".join(s))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)

alphabets = "abcdefghijklmnopqrstuvwxyz"
a = {c:i for i, c in enumerate(alphabets)}
s = list(input())
n = len(s)
k = int(input())

def f(k, i):
    if i == n - 1:
        k_ = k % 26
        c = s[i]
        shifted = (k_ + a[c]) % 26
        return alphabets[shifted]

    c = s[i]
    diff = 26 - a[c]
    if c != "a" and diff <= k:
        return "a" + f(k-diff, i+1)
    else:
        return c + f(k, i+1)
        

print(f(k, 0))

Submission status: Accepted

Solution code:
s=input()
l=len(s)
k=int(input())
z=''
for i in range(l):
  t=123-ord(s[i])
  if s[i]=='a':
    z+='a'
  elif t<=k:
    z+='a'
    k-=t
  else:
    z+=s[i]
v=ord(z[l-1])-97+k
z=z[:l-1]+chr(v%26+97)
print(z)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(4100000)

import math

import logging

logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger(__name__)


def resolve():
    S = [x for x in sys.stdin.readline().split()][0]  # 文字列 一つ
    K = [int(x) for x in sys.stdin.readline().split()][0]  # int 一つ
    # N, D = [int(x) for x in sys.stdin.readline().split()]  # 複数int
    # h_list = [int(x) for x in sys.stdin.readline().split()]  # 複数int

    # grid = [list(sys.stdin.readline().split()[0]) for _ in range(N)]  # 文字列grid
    # v_list = [int(sys.stdin.readline().split()[0]) for _ in range(N)]
    # grid = [[int(x) for x in sys.stdin.readline().split()]
    #         for _ in range(N)]  # int grid

    logger.debug('{}'.format([]))

    a_ord = ord("a")
    z_index = ord("z") - a_ord

    s_ord = [ord(s) - a_ord for s in S]
    for i, s in enumerate(s_ord):
        if z_index + 1 - s > K or s == 0:
            continue
        else:
            s_ord[i] = 0
            K -= z_index - s + 1

    mod = ord("z") - a_ord + 1
    if K > 0:
        K = K % mod
        s_ord[-1] = (s_ord[-1] + K) % mod

    print("".join([chr(x + a_ord) for x in s_ord]))


if __name__ == "__main__":
    resolve()

# AtCoder Unit Test で自動生成できる, 最後のunittest.main は消す
# python -m unittest template/template.py で実行できる
# pypy3 -m unittest template/template.py で実行できる
import sys
from io import StringIO
import unittest


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """xyz
4"""
        output = """aya"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """a
25"""
        output = """z"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """codefestival
100"""
        output = """aaaafeaaivap"""
        self.assertIO(input, output)

Submission status: Accepted

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

for i in range(len(s)):
        if ord("z")-ord(s[i])+1<=k:
                k -= (ord("z")-ord(s[i])+1)%26
                s[i] = "a"
if k: s[-1] = chr((ord(s[-1])+k-ord("a"))%26+ord("a"))
print("".join(s))

Submission status: Accepted

Solution code:
if __name__ == "__main__":
    s = input()
    k = int(input())

    s_num = [0] * len(s)
    res = k
    for i in range(len(s)):
        tmp = ord(s[i]) - 97
        if tmp != 0 and 26 - tmp <= res:
            res -= (26 - tmp)
            s_num[i] = 0
        else:
            s_num[i] = tmp

    res %= 26

    s_num[-1] += res

    ans = ''
    for i in s_num:
        ans += chr(i + 97)

    print(ans)

Submission status: Accepted

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

for i in range(len(s)):
    if k==0:break

    num=ord(s[i])
    ch_num=123-num
    if i==len(s)-1:
        s[i]=chr(97+(num+k-97)%26) #if num+k>122 else chr(num+k)
        #print(97+(num+k-97)%26)
        k=0
        break
    elif s[i]=='a':continue
    elif ch_num<=k:
        s[i]='a'
        k-=ch_num
print(''.join(s))

Submission status: Accepted

Solution code:
t="abcdefghijklmnopqrstuvwxyz"
s=input()
k=int(input())
a=[t.index(i)for i in s]
ans=""
for i in a:
  j=i
  if i==0:
    ans+="a"
    continue
  if k>=26-i:
    k-=26-i
    j=0
  ans+=t[j]
j+=k
j%=26
ans=ans[:-1]+t[j]
print(ans)

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
cnt = 0
ans = ''
for i in range(len(s)):
    cnt = (ord('z') - ord(s[i]) + 1) % 26
    if cnt <= k:
        k -= cnt
        s[i] = 'a'
s[-1] = chr((ord(s[-1]) - ord('a') + k) % 26 + ord('a'))
print(*s, sep='')

Submission status: Accepted

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

ans = []

for i in s:
    if i == "a":
        ans.append("a")
        continue
    
    if ord(i) + K >= ord("z") + 1:
        ans.append("a")
        K -= ord("z") + 1 - ord(i)
    
    else:
        ans.append(i)
        


last = (K + ord(ans[-1]) - ord('a')) % 26
ans[-1] = chr(ord("a") + last)
print(''.join(ans))

Submission status: Accepted

Solution code:
#print(ord('a')) # 97
abc = ''
for i in range(97 ,97+26):
    abc += chr(i)
#print(abc)

S = input()
K = int(input())
ans = ''
for i,s in enumerate(S):
    if ord(s) > ord('a') and 26 - (ord(s) - ord('a')) <= K and i!=len(S)-1:
        ans += 'a'
        #K -= 26 - (ord(s) - ord('a'))
        K -= 26 - (ord(s) - ord('a'))
        #print(K)

    elif i != len(S)-1:
        ans += s
    else:
        #ans += chr(ord(s) + K%26)
        ans += abc[(ord(s) + K%26-ord('a'))%26]
        #print(ans)

print(ans)

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
def input(): return sys.stdin.readline().strip()
def STR(): return input()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
sys.setrecursionlimit(10 ** 9)
inf = sys.maxsize
mod = 10 ** 9 + 7

s = list(STR())
l = len(s)
k = INT()
for i in range(l):
    tmp = (ord('z') - ord(s[i]) + 1) % 26
    if tmp <= k:
        s[i] = 'a'
        k -= tmp
    #print(k, tmp)
s[l - 1] = chr((ord(s[l - 1]) - ord('a') + k) % 26 + ord('a'))
print(''.join(s))

Submission status: Accepted

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

n = len(s)

l = [0]*n
for i in range(n):
    l[i] = ord('z') -ord(s[i]) + 1
    l[i] %= 26
#print(l)

ans = list(s)
i = 0
while k > 0:
    if i > n-1:
        break
    if l[i] <= k:
        ans[i] = 'a'
        k -= l[i]
    i += 1
k %= 26
if k > 0:
    ans[-1] = chr((k + ord(ans[-1])-ord('a'))%26+97)
#print(ans)
print(''.join(ans))

Submission status: Accepted

Solution code:
import sys
def main():
    input = sys.stdin.readline
    s = input().rstrip()
    K = int(input())

    def c(x): return ord(x) - ord('a')
    def d(x): return chr(x + ord('a'))
    ans = []
    i = 0
    while i < (len(s) - 1):
        to_a = (26 - c(s[i])) % 26
        if to_a <= K:
            ans.append('a')
            K -= to_a
        else:
            ans.append(s[i])
        i += 1
    if K > 0:
        ans.append(d((c(s[-1]) + K) % 26))
    else:
        ans.append(s[i])
    print(''.join(ans))

if __name__ == '__main__':
    main()

Submission status: Accepted

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

"""
Kを使用する
-> aにすることができる

残りのKはs[-1]に使用
"""

from collections import defaultdict
alpha = defaultdict(int)
for i in range(97, 97 + 26):
    alpha[chr(i)] = i - 97

for i in range(len(s)):
    if s[i] == "a":
        continue
    if 26 - alpha[s[i]] <= K:
        K -= 26 - alpha[s[i]]
        s[i] = "a"

if K > 0:
    s[-1] = chr(97 + (alpha[s[-1]] + K) % 26)

print(*s, sep="")

Submission status: Accepted

Solution code:
def main():
    S = input()
    N = len(S)
    K = int(input())
    from string import ascii_lowercase
    dic = {a: i for i, a in enumerate(ascii_lowercase)}
    rdic = {i: a for i, a in enumerate(ascii_lowercase)}
    li = [(26 - dic[s]) % 26 for s in S]
    ans = []
    # print(li)
    for i, cnt in enumerate(li):
        if i == N - 1:
            ans.append(rdic[(dic[S[i]] + K) % 26])
            continue
        if cnt <= K:
            K -= cnt
            ans.append("a")
        else:
            ans.append(S[i])
    print("".join(ans))


if __name__ == '__main__':
    main()

Submission status: Accepted

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

ans = ''
for s in S:
    to_a_cost = (26 - (ord(s) - 97)) % 26
    if to_a_cost <= K:
        ans += 'a'
        K -= to_a_cost
    else:
        ans += s


if K:
    K %= 26
    ans = ans[:-1] + chr(97 + (((ord(ans[-1]) - 97) + K) % 26))

print(ans)

Submission status: Accepted

Solution code:
import sys

class alphabet(): #Trueなら大文字
    def __init__(self, capitalize):
        self.num = dict() #あるアルファベットが最初から何番目か、0-indexed
        self.index = dict() #i番目のアルファベット
        self.abc = ["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"]
        if capitalize: 
            for i in range(26): self.abc[i] = self.abc[i].upper()
        for i, a in enumerate(self.abc):
            self.num[a] = i
            self.index[i] = a

def solve():
    S = list(input())
    length = len(S)
    K = int(input())
    changed = 0
    AB = alphabet(False)
    for i, s in enumerate(S):
        aId = AB.num[s]
        if aId == 0: continue
        else:
            toA = 26 - aId
            if K - changed >= toA: 
                S[i] = "a"
                changed += toA
    if K - changed > 0:
        aId = AB.num[S[length - 1]]
        S[length - 1] = AB.index[(aId + K - changed) % 26]
    print("".join(map(str, S)))
    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
S = list(input())
K = int(input())

for i in range(len(S)):
    if S[i] == 'a':
        continue

    d = ord('z') - ord(S[i]) + 1
    if K >= d:
        S[i] = 'a'
        K -= d
    # print(K, d)

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

print(''.join(S))

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_right, bisect_left
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, gamma, log
from operator import mul
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)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7


D = {c:i for i,c in enumerate('abcdefghijklmnopqrstuvwxyz')}
a = 'abcdefghijklmnopqrstuvwxyz'
s = S()
k = I()
ans = []
cnt = 0
for i in s:
    if 26 - D[i] <= k and i != 'a':
        k -= 26 - D[i]
        ans += ['a']
    else:
        ans += [i]

if k:
    ans[-1] = a[D[ans[-1]] + k % 26]


print(''.join(ans))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def main():
    s = input().rstrip()
    k = int(input())
    for i in range(len(s)):
        x = ord("z") - ord(s[i]) + 1
        if k >= x and x != 26:
            k -= x
            s = s[:i] + "a" + s[i+1:]
        if i == len(s)-1:
            s = s[:i] + (chr(ord(s[i]) + (k%26)))
    print(s)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
for i in range(len(s)):
    if s[i] != "a" and (123-ord(s[i])) <= k:
        k -= (123-ord(s[i]))
        s[i] = "a"
    if i == len(s)-1:
        s[i] = (chr((((ord(s[i])+(k%26))-97)%26)+97))
print("".join(s))

Submission status: Accepted

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

print("".join(s))



# a = "z"
# a = ord(a)
# print(a)

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

s = input()
n = len(s)
r = [ord('z') - ord(t) + 1 if t != 'a' else 0 for t in s]
res = [None] * n
k = inp()
for i,x in enumerate(r):
    if x <= k:
        res[i] = 'a'
        k -= x
if k > 0:
    tmp = 'a' if res[-1] != None else s[-1]
    res[-1] = chr((ord(tmp) - ord('a') + k)%26 + ord('a'))
for i,t in enumerate(res):
    if t == None:
        res[i] = s[i]
print(''.join(res))

Submission status: Accepted

Solution code:
s = list(input())
K = int(input())
def plus(c,i):
    return chr((ord(c)-ord('a')+i)%26+ord('a'))
# 上から順に回るなら回す
for i,ss in enumerate(s):
    want = (ord('z') + 1 - ord(ss))%26
    if K >= want:
        s[i] = plus(s[i],want)
        K = K - want
    
K = K % 26
if K >= 1:
    s[-1] = plus(s[-1],K)
print("".join(s))

Submission status: Accepted

Solution code:
#codinf utf-8
s = list(input())
K = int(input())
N = len(s)
alp = [chr(i) for i in range(97, 97+26)]

for i in range(N):
    idx = alp.index(s[i])
    
    if K + idx >= 26 and idx != 0:
        K = K - ( 26 - idx )
        s[i] = 'a'
    if K == 0:
        break
    
if K > 0:
    id = alp.index(s[N-1])

    id_ = ( id + K ) % 26

    s[N-1] = alp[id_]

print(''.join(s))

Submission status: Accepted

Solution code:
S=list(input())
K=int(input())
N=len(S)
for i in range(N):
  k=(ord('z')-ord(S[i])+1)%26
  if K>=k:
    S[i]='a'
    K-=k
S[-1]=chr(ord(S[-1])+K%26)
print(''.join(S))

Submission status: Accepted

Solution code:
alp = "abcdefghijklmnopqrstuvwxyz"
s = input()
K = int(input())
N = len(s)
T = ""
for i in range(N):
    n = alp.index(s[i])
    if i==N-1:
        T+=alp[(n+K)%26]
    else:
        if n!=0 and K>=26-n:
            T+="a"
            K-=(26-n)
        else:T+=alp[n]
print(T)

Submission status: Accepted

Solution code:
s=list(input())
K=int(input())
A=[chr(ord('a') + i) for i in range(26)]+[chr(ord('a') + i) for i in range(26)]
for i in range(len(s)):
  a=A.index(s[i])
  if i==len(s)-1:
    K%=26
    s[i]=A[a+K]
    break
  if s[i]=='a':
    continue
  if K>=26-a:
    K-=(26-a)
    s[i]='a'
  else:
    continue
print(*s,sep='')