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:
S = str(input())
K = int(input())

N = len(S)

L = []

for i in range (0, N):
	L.append((97-ord(S[i]))%26)

W = []

for i in range (0, N-1):
	if L[i] <= K:
		W.append('a')
		K -= L[i]
	else:
		W.append(S[i])

V = (26-L[N-1]+K)%26
W.append(chr(97+V))
print(*W, sep="")

Submission status: Accepted

Solution code:
def main():
    S = list(input())
    K = int(input())
    k = K
    for i,c in enumerate(S):
        distance = (ord('z') + 1 - ord(c))%26
        if distance <= k:
            k -= distance
            S[i] = 'a'
    S[-1] = chr((ord(S[-1]) - ord('a') + k) % 26 + ord('a'))
    print(''.join(S))

main()

Submission status: Accepted

Solution code:
s = input()
k = int(input())
ans = ""
for i in range(len(s)-1):
    cost = ord("z")+1-ord(s[i])
    if s[i] == "a" or k < cost:
        ans += s[i]
    else:
        ans += "a"
        k -= cost
c = s[-1]
k %= 26
for _ in range(k):
    if c == "z": c = "a"
    else: c = chr(ord(c)+1)
ans += c
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log,gcd
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')

#Pythonを用いる場合
#numpy 1.18.0, scipy 1.4.1, scikit-learn 0.22, numba 0.47.0, networkx 2.4
 
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

s=list(ss())
k=ii()
ans=""
for i in range(len(s)):
    p=ord(s[i])
    
    if i==len(s)-1:
        k%=122-97+1
        #print(k)
        p+=k
        if p>=123:
            p-=122-97+1
        ans=ans+chr(p)
        #print(p)
    elif s[i]=="a":
        ans=ans+"a"
    elif k>=123-p:
        k-=123-p
        ans=ans+"a"
    else:
        ans=ans+s[i]

print(ans)

Submission status: Accepted

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from math import factorial, sqrt, ceil, gcd
from functools import lru_cache, reduce
from decimal import Decimal
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)

# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret

def make_divisors(n):
    lower_divisors , upper_divisors = [], []
    i = 1
    while i*i <= n:
        if n % i == 0:
            lower_divisors.append(i)
            if i != n // i:
                upper_divisors.append(n//i)
        i += 1
    return lower_divisors + upper_divisors[::-1]

# ここから書き始める
s = input()
k = int(input())

cnt = 0
n = len(s)
ans = [i for i in s]
for i in range(n):
    # print("cnt =", cnt)
    if cnt == k:
        break
    cost = ord("z") + 1 - ord(ans[i])
    if i == n - 1:
        cost2 = cost - 1
        # print(k - cnt <= cost2)
        if k - cnt <= cost2:
            ans[i] = chr(ord(ans[i]) + k - cnt)
        else:
            k2 = k - cnt - cost2
            if k2 % 26 == 0:
                ans[i] = "z"
            else:
                ans[i] = chr(ord("a") + k2 % 26 - 1)
        break
    if ans[i] == "a":
        continue  
    if k - cnt >= cost:
        cnt += cost
        ans[i] = "a"
print("".join(ans))

Submission status: Accepted

Solution code:
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
print("".join(map(encode, S)))

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
n = len(s)
map = {(chr(ord("a") + i)): (26-i)%26 for i in range(26)}
for i in range(n):
    if k >= map[s[i]]:
        k -= map[s[i]]
        s[i] = "a"
if k > 0:
    s[n-1] = chr((ord(s[n-1])+k%26)%123)
print("".join(s))

Submission status: Accepted

Solution code:
s=list(input())
K=int(input())
alp=["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"]

for i in range(len(s)):
    n=alp.index(s[i])
    if n!=0 and n+K>=26:
        s[i]="a"
        K-=26-n
    if i==len(s)-1 and K>0:
        n=alp.index(s[i])
        s[i]=alp[(n+K)%26]

for j in s:
    print(j,end="")
print()

Submission status: Accepted

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

ord_a = ord('a')
ord_z = ord('z')

k = K
Ans = list(S)
for i, s in enumerate(S[:-1]):
    ord_s = ord(s)
    dif = ord_z - ord_s + 1
#    print(i, k, dif)
    if s == 'a':
        Ans[i] = 'a'
    elif dif <= k:
        Ans[i] = 'a'
        k -= dif
    else:
        pass
Ans[-1] = chr(ord_a + (ord(Ans[-1]) + k - ord_a)%26)
print(''.join(Ans))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache


#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AtoZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)


#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
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

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
S = S()
N = I()
L = [ord(s)-97 for s in S]

for i in range(len(L)):
  if i == len(L)-1:
    L[i] = (L[i] + N)%26
  elif L[i] == 0:
    continue
  elif 26-L[i]<=N:
    temp = 26-L[i]
    L[i] = 0
    N -= temp
  else:
    continue
    
print(*[chr(i+97) for i in L],sep="")

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7
 
S = list(readline().rstrip())
K = int(readline())
N = len(S)
for i,s in enumerate(S):
    t = ord(s)-97
    if t == 0:
        continue
    if 26 - t <= K:
        S[i] = 'a'
        K -= 26-t
S[-1] = chr((ord(S[i]) + K%26)%97+97)
print(''.join(S))

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7

S = list(readline().rstrip())
K = int(readline())
N = len(S)
for i in range(N):
    t = ord(S[i])-97
    if t == 0:
        continue
    if 26 - t <= K:
        S[i] = 'a'
        K -= 26-t
S[-1] = chr((ord(S[-1])-97 + K%26)%26 + 97)
print(''.join(S))

Submission status: Accepted

Solution code:
def str_rotate(S,k): # str_rotate(str,int)
    if k >= 26:
        k = k%26
    if ord(S) + k > 123:
        S = chr(ord(S)+k-97)
    else:
        S = chr(ord(S)+k)
    return S

s = list(input())
k = int(input())
for i in range(len(s)):
    if k == 0:
        break
    if s[i] == "a":
        pass
    elif 123 - ord(s[i]) <= k:
        k -= 123 - ord(s[i])
        s[i] = "a"
    else:
        pass
s[-1] = str_rotate(s[-1],k)
print("".join(s))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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 d <= K:
        s[i] = "a"
        K -= d

x = (ord(s[-1])-ord("a")+K)%26
s[-1] = chr(ord("a")+x)
print("".join(s))

Submission status: Accepted

Solution code:
s = input()
K = int(input())
alh = [chr(i) for i in range(97, 97 + 26)]
ans = ""
d = {}
for n,i in enumerate(alh):
    d[i] = (26-n)%26
for i in s[:-1]:
    if K >= d[i]:
        K -=d[i]
        ans += "a"
    else:
        ans += i
ans += chr(97+(ord(s[-1])+K-97)%26)
print(ans)

Submission status: Accepted

Solution code:
G={chr(a+ord("a")):a for a in range(26)}
H={G[b]:b for b in G}

T=input()
S=[]
for s in T:
    S.append(G[s])
K=int(input())

I=0
N=len(S)
for i in range(N):
    if (i<N-1) and (26-S[i]<=K) and S[i]!=0:
        K-=26-S[i]
        S[i]=0
    elif i==N-1:
        S[i]=(S[i]+(K%26))%26

U=""
for s in S:
    U+=H[s]

print(U)

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
n = len(s)
for i in range(n):
    if s[i]=='a':continue
    d = ord('z')-ord(s[i])+1
    if d<=k:
        s[i] = 'a'
        k -= d

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

print(''.join(s))

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
n = len(s)
for i in range(n-1):
    d = (ord('z')-ord(s[i])+1)%26
    if d<=k:
        s[i] = 'a'
        k -= d

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


print(''.join(s))

Submission status: Accepted

Solution code:
makeA = lambda c: (ord('z')-ord(c)+1) % 26
s = list(map(makeA,list(input())))
#print(s)
K = int(input())
len_s = len(s)
#print(len_s)
for i in range(len_s-1):
    if s[i] <= K:
        K -= s[i]
        s[i] = 0
        #print(s)
if K > 0:
    s[-1] = (s[-1] + 26 - (K % 26)) % 26
#print(s)
makeS = lambda n: chr((26-n)%26+ord('a'))
print(''.join(list(map(makeS,s))))

Submission status: Accepted

Solution code:
S = input()
K = int(input())
z = ord('z') + 1

res = ""
flg = False
for i,c in enumerate(S):
    if c == 'a':
        res += 'a'
        continue
    elif z - ord(c) <= K:
        res += 'a'
        K -= z-ord(c)
    else:
        res += chr(ord(c))

res = res[:-1] + chr((ord(res[-1])-ord('a') + K) % 26 + ord('a'))
print(res)

Submission status: Accepted

Solution code:
def main():
    S = list(input())
    k = int(input())
    ans = []
    for s in S:
        if s != 'a' and ord(s) >= 123 - k:
            ans.append('a')
            k -= 123 - ord(s)
        else:
            ans.append(s)
    if k > 0:
        ans[-1] = chr((ord(ans[-1]) + k - 97) % 26 + 97)
    print(''.join(ans))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


def solve():
    s = rl().rstrip()
    K = int(rl())
    
    ans = []
    for si in s:
        if si == 'a':
            ans.append('a')
            continue
        cnt = ord('z') - ord(si) + 1
        if cnt <= K:
            ans.append('a')
            K -= cnt
        else:
            ans.append(si)
    
    ans[-1] = chr(ord('a') + (ord(ans[-1]) - ord('a') + K % 26) % 26)
    print(''.join(ans))


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
s = str(input())
k = int(input())
S = []
for i in range(len(s)):
    S.append(ord(s[i]) - 97)
i = 0
while k > 0:
    if S[i] > 0 and 26 - S[i] <= k:
        k -= 26 - S[i]
        S[i] = 0
        i += 1
    else:
        i += 1
    if i >= len(s):
        S[-1] += k
        break
ans = ''
for x in S:
    ans += chr((x % 26) + 97)
print(ans)

Submission status: Accepted

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

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

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
s = list(map(str, input().rstrip()))
k = int(input())

diff = [(ord("a") + 26 - ord(x)) % 26 for x in s]

for i in range(len(s) - 1):
    if diff[i] <= k:
        s[i] = "a"
        k -= diff[i]
    else:
        continue

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

s[-1] = chr(tmp)

print("".join(s))

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

s = list(input())
K = INT()

def ctoi(c):
	return ord(c)-ord("a")

for i in range(len(s)):
	x = ctoi(s[i])
	if x == 0 or 26-x > K:
		continue
	K -= 26 - x
	s[i] = "a"

if K:
	s[-1] = ascii_lowercase[(ctoi(s[-1])+K)%26]

print("".join(s))

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

s = list(input())
K = INT()

for i in range(len(s)):
	tmp = 26 - ascii_lowercase.index(s[i])
	if tmp <= K and tmp < 26:
		K -= tmp
		s[i] = "a"

idx = ascii_lowercase.index(s[-1])
s[-1] = ascii_lowercase[(idx+K)%26]

print(*s, sep="")

Submission status: Accepted

Solution code:
import sys
from io import StringIO
import unittest
import os


# 実装を行う関数
def resolve():
    s = list(input())
    k = int(input())

    # 各桁をaにするために必要な処理回数を求める。(1桁ずつ求めていく)
    need_cnt_list = [26 - (ord(i) % 97) for i in s]
    # アルファベット(小文字)のaASCIIは97。なので、mod97でアルファベットを番号に置換できる(a=0 z=25)。ちなみに大文字Aは65。
    # for i in s:
    #     work += 26 - (ord(i) % 97)

    ans = []

    zan_cnt = k

    for num, i in enumerate(need_cnt_list):
        # 値がaの場合何もしない(既に最適解)
        if s[num] == "a":
            ans.append("a")
        # 値を1週させてaにできる場合、該当文字をaにする。
        elif zan_cnt >= i:
            zan_cnt -= i
            # 該当文字をaにする。
            ans.append("a")
        # 値を1週させてaにできない場合、その桁は何も処理せず次の桁に進む。
        else:
            ans.append(s[num])

    # 最後に、最終桁を延々と処理した結果が答え。
    # ※「余ったkを全て最終桁に使用した場合の最終桁の文字」で最終文字を置換
    now_last = ord(ans[-1]) - 97
    last = zan_cnt % 26 + now_last

    # 最終桁の文字を置き換え
    ans[-1] = chr(last + 97)
    print("".join(ans))
    return


# テストクラス
class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """xyz
4"""
        output = """aya"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """a
25"""
        output = """z"""
        self.assertIO(test_input, output)

    def test_input_3(self):
        test_input = """codefestival
100"""
        output = """aaaafeaaivap"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def test_1original_1(self):
        test_input = """bbb
100000000"""
        output = """aaz"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def test_1original_2(self):
        test_input = """bbb
75"""
        output = """aaa"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def test_1original_2(self):
        test_input = """bbc
74"""
        output = """aaa"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def test_1original_3(self):
            test_input = """bba
74"""
            output = """aay"""
            self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()

Submission status: Accepted

Solution code:
s=list(input())
n=len(s)
k=int(input())
a=[]
for i in range(n):
  if i==n-1:
    s[i]=chr(97+(ord(s[i])-97+k)%26)
    break
  if s[i]=="a":continue
  t=26-(ord(s[i])-97)%26
  if t>k:continue
  k-=min(t,k)
  s[i]=chr(97+(ord(s[i])-97+t)%26)
print("".join(s))

Submission status: Accepted

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

ans = []
for c in s[:-1]:
    to_a = (ord('z')-ord(c)+1) % 26
    if k < to_a:
        ans.append(c)
    else:
        k -= to_a
        ans.append('a')
else:
    c = s[-1]
    x = ord(c)-ord('a')
    y = (k+x) % 26
    ans.append(chr(ord('a')+y))


print(''.join(ans))

Submission status: Accepted

Solution code:
s=list(input())
K=int(input())
for i in range(len(s)):
    if i==len(s)-1:
        K=K%26
        x=ord(s[i])
        for j in range(K):
            x+=1
            if x==123:
                x=97
        s[i]=chr(x)
    else:
        if K<=0 or s[i]=='a':
            continue
        dif=123-ord(s[i])
        if dif<=K:
            s[i]='a'
            K-=dif
print(''.join(s))

Submission status: Accepted

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

'''
ordの位置
#z = 122
#a = 97
左の文字からNで'a'に出来るかを確認
aに出来るならaにして使った分をNから引く
繰り返して行き一番最後にあまりをすべて使う
'''
  
for i, s in enumerate(S):
  if ord(s) - 97 > 0  and 122 - ord(s) < N:
    S[i] = "a"
    N -= 123 - ord(s)
else:
  S[i] = chr(N % 26 + ord(S[i])) # ここのWAは反省する
       
print("".join(S))

Submission status: Accepted

Solution code:
from collections import deque
s = input()
k = int(input())
a = ord("a")
l = deque(list())
l1 = []
for i in range(len(s)):
  s1 = s[i]
  l.append(((a+26)-ord(s1))%26)
#print(l)
while k!=0:
    if len(l)!=0:
        t = l.popleft()
        if k>=t:
            l1.append("a")
            k -= t
        else:
          if t=="a":
            l1.append(t)
          else:
            l1.append(chr((ord('a')-t+26)))
    else:
      k %= 26
      l1[-1] = chr(int(ord(l1[-1])+k))
      k = 0
l2 = []
if len(l)>=1:
  for t in l:
    t %= 26
    if t==0:
      l2.append("a")
    else:
      l2.append(chr((ord('a')-t+26)))
  l1 += l2
print("".join(l1))

Submission status: Accepted

Solution code:
alpha = "abcdefghijklmnopqrstuvwxyz"
A = ["a"]+[i for i in alpha[::-1]]
s = list(input())
k = int(input())
n = len(s)
for i in range(n):
    if s[i] == "a":
        continue
    j = A.index(s[i])
    if j <= k:
        s[i] = "a"
        k -= j
    if k == 0:
        print("".join(s))
        exit()
else:
    k %= 26
    l = alpha.index(s[-1])
    if l + k <= 25:
        s[-1] = alpha[k+l]
    else:
        s[-1] = alpha[k+l-26]
    print("".join(s))

Submission status: Accepted

Solution code:
alphabet = 'abcdefghijklmnopqrstuvwxyz'
s = input()
K = int(input())
ans = ''
for i in range(len(s) - 1):
    s_i = alphabet.index(s[i])
    if s[i] == 'a':
        ans += 'a'
        continue
    if (26 - s_i <= K):
        K -= 26 - s_i
        ans += 'a'
    else:
        ans += s[i]
ans += alphabet[(K + alphabet.index(s[-1])) % 26]
print(ans)

Submission status: Accepted

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

ans = []

for i in range(len(s)):
    if 123 - ord(s[i]) <= k:
        if s[i] == "a":
            ans.append("a")
            continue
        ans.append("a")
        k -= 123 - ord(s[i])
    else:
        ans.append(s[i])

last = chr((ord(ans[-1])-97+k)%26 + 97)
ans[-1] = last


print(*ans, sep = "")

Submission status: Accepted

Solution code:
# input()
# int(input())
# map(int, input().split())
# list(map(int, input().split()))
# list(map(int, list(input()))) # スペースがない数字リストを読み込み
import math
import sys
import bisect
import heapq  # 優先度付きキュー(最小値取り出し)
from collections import deque
inf = 10**18
mod = 10**9+7

s = input()
k = int(input())
n = len(s)
ans = []
for c in s[:n-1]:
    if c == 'a':
        ans.append('a')
        continue
    if ord('z')-ord(c)+1 <= k:
        k-=(ord('z')-ord(c)+1)
        ans.append('a')
    else:
        ans.append(c)
ans.append(chr(ord('a')+(ord(s[n-1])-ord('a')+k)%26))
print(*ans, sep='')

Submission status: Accepted

Solution code:
S=list(input())
k=int(input())
for i in range(len(S)):
    s=S[i]
    if s=="a":continue
    x=123-ord(s)
    #print(s,x,ord("z"))
    if k>=x:
        k-=x
        S[i]="a"

    else:continue
k%=26
for i in range(len(S)):
    if S[-1-i]!="a":
        S[-1-i]=chr((ord(S[-1-i])-97+k%26)+97)
        print("".join(S));break
else:
    S[-1]=chr((ord(S[-1])-97+k%26)+97)
    print("".join(S))

Submission status: Accepted

Solution code:
s = input()
k = int(input())
d = {}
dd = {}
for i, ss in enumerate('abcdefghijklmnopqrstuvwxyz'):
    d[ss] = i
    dd[i] = ss
ans = ''

for ss in s[:-1]:
    if k >= 26 - d[ss] and ss != 'a':
        k -= 26 - d[ss]
        ans += 'a'
    else:
        ans += ss
k = (d[s[-1]] + k) % 26
ans += dd[k]
print(*ans, sep='')

Submission status: Accepted

Solution code:
s = list(input())
k = int(input())
for i in range(len(s)):
    if s[i] == "a":
        continue
    c = ord(s[i]) - ord("a")
    if k >= (26 - c):
        k -= 26 - c
        s[i] = "a"
s[-1] = chr(((ord(s[-1]) - ord("a")) + k) % 26 + ord("a"))
print("".join(s))

Submission status: Accepted

Solution code:
s=list(map(ord,list(input())))
k=int(input())

for i in range(len(s)):
    s[i]-=97

c=0
while k>0:
    if c==len(s)-1:
        s[c]=(s[c]+k)%26
        k=0
    elif s[c]==0:
        c+=1
    elif s[c]+k>=26:
        k-=26-s[c]
        s[c]=0
        c+=1
    else:
        c+=1

seq=""
for i in range(len(s)):
    seq+=chr(s[i]+97)

print(seq)

Submission status: Accepted

Solution code:
import sys

# import re
import math
import collections
# import decimal
import bisect
import itertools
import fractions
# import functools
import copy
import heapq
import decimal
# import statistics
import queue
import numpy as np

sys.setrecursionlimit(10000001)
INF = 10 ** 16
MOD = 10 ** 9 + 7

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))


# ===CODE===


def main():
    s = list(input())
    k = ni()

    for i in range(len(s)):
        if s[i] == "a":
            continue
        si = ord(s[i]) - 97
        if k >= 26 - si:
            s[i] = "a"
            k -= 26 - si
            if k == 0:
                break

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

    print(*s, sep="")


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
al=[chr(ord('a') + i) for i in range(26)]
s=input()
N=len(s)
K=int(input())

for i in range(N):
  if i<N-1:
    a=26-al.index(s[i])
    if K>=a and s[i]!="a":
      K -= a
      s=s[0:i]+al[(al.index(s[i])+a)%26]+s[i+1:]
  else:
    K %= 26
    p= (K+al.index(s[i]))% 26
    s=s[0:N-1]+al[p]
    K=0
    
print(s)