문제
- N개의 36진법 문자를 입력받음
- K개의 특정 문자를 Z로 바꿨을 때, 입력 받은 모든 숫자의 합으로 최대가 될 수 있는 값을 36진수의 수로 출력
과정
- 0부터 Z까지 값을 저장할 리스트를 만듦
- 단어를 입력 받으며, 각 문자마다 Z로 변환했을 때, 생길 이익을 리스트에 저장
- 리스트에서 최대 K개 수의 합을 입력 받은 모든 수 합에 더함
- 더한 값을 36진수로 변환해서 출력
시행착오
- ord 사용하는 과정에서 헷갈림
- 36진수이므로 이익 본 만큼의 수를 구하려면 36^(자리수) 를 해야 함
- 이를 생각 안하고 단순히 문자 출현 횟수만을 구하려했음.
반례
- 0이 입력으로 들어온 경우
- 36진수로 변경할 때, 0이 들어온 경우를 예외처리 해야한다.
- 안했더니 아무 것도 출력하지 않음.
import sys
N = int(input())
score_total = 0
profit = [0] * 36
# 해당 문자를 Z로 변환함으로서 얻을 수 있는 이익을 저장
for _ in range(N):
inp = sys.stdin.readline().rstrip()
for i in range(len(inp)):
if inp[i].isnumeric():
score_total += int(inp[i]) * (36 ** (len(inp) - i - 1))
profit[int(inp[i])] += (35 - int(inp[i])) * (36 ** (len(inp) - i - 1))
else:
score_total += (ord(inp[i]) - 55) * (36 ** (len(inp) - i - 1))
profit[ord(inp[i]) - 55] += (35 - (ord(inp[i]) - 55)) * (36 ** (len(inp) - i - 1))
K = int(input())
# profit 에서 최대인 값 K 개를 구하고
profit_total = 0
profit.sort(reverse=True)
for i in range(K):
profit_total += profit[i]
# 전체 값에 더하기
score_total += profit_total
# 36진수로 변경하기
def to36(num):
j = 0
ans = ""
if num == 0:
return "0"
while True:
if num < 36 ** j:
break
j += 1
while True:
j -= 1
if j < 0:
break
add_ans, remain = divmod(num, 36 ** j)
if 0 <= add_ans < 10:
ans += str(add_ans)
else:
ans += chr(add_ans + 55)
num = remain
return ans
print(to36(score_total))