Post

[SWEA] 13428. ์ˆซ์ž ์กฐ์ž‘(python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

๐Ÿ’ช์•„์ด๋””์–ด

  1. ์ˆ˜ ๋‚˜์—ดํ•˜๊ธฐ
    ์ธ๋ฑ์Šค๋ณ„๋กœ ๊ฒ€์‚ฌํ•˜๋ฉด์„œ ์ž…๋ ฅ๋œ string[i]์™€ ์ž‘์€ ์ˆ˜(์ตœ์†Ÿ๊ฐ’์˜ ๊ฒฝ์šฐ)/ํฐ ์ˆ˜(์ตœ๋Œ“๊ฐ’์˜ ๊ฒฝ์šฐ) ๋น„๊ตํ•˜๋‹ค๊ฐ€ ํ•ด๋‹น์ธ๋ฑ์Šค์˜ ๊ฐ‘์†Œ๊ฐ€ ์ˆ˜๊ฐ€ ๋‹ค๋ฅด๋ฉด ์ž๋ฆฌ๋ฅผ ๋ฐ”๊ฟ”์ค€๋‹ค. string์— ์ž‘์€ ์ˆ˜์™€ ํฐ ์ˆ˜๋ฅผ ๋น„๊ตํ•˜๊ธฐ์œ„ํ•˜์—ฌ min heap๊ณผ max heap์„ ์‚ฌ์šฉํ•˜์˜€๋‹ค
  2. 0 ์ฒ˜๋ฆฌํ•˜๊ธฐ
    ์ž…๋ ฅ๊ฐ’์ด 0์ด ๋“ค์–ด์˜จ ๊ฒฝ์šฐ๋ฅผ ์ œ์™ธํ•˜๊ณ ๋Š” ์ธ๋ฑ์Šค 0์— โ€˜0โ€™์ด ์˜ฌ ์ˆ˜ ์—†๋‹ค. ๋”ฐ๋ผ์„œ ์ตœ์†Ÿ๊ฐ’์„ ์ฒ˜๋ฆฌํ•  ๋•Œ min heap์— 0์ด ์žˆ์„ ์ˆ˜ ์žˆ์œผ๋‹ˆ ์ธ๋ฑ์Šค 0์„ ๊ฒ€์‚ฌ ํ›„์— min heap์— 0์„ ๋„ฃ๋„๋ก ํ•˜์˜€๋‹ค. max heap์€ heap์„ ์ƒ์„ฑํ•  ๋–„ 0์„ ๋„ฃ์–ด๋„ ์ƒ๊ด€์ด ์—†์œผ๋‚˜ ํ•จ์ˆ˜์˜ ์žฌ์‚ฌ์šฉ์„ ์œ„ํ•˜์—ฌ max heap์ƒ์„ฑ์‹œ์— 0์„ ๋„ฃ์–ด์ฃผ์ง€ ์•Š์•˜๋‹ค.
  3. ์ž๋ฆฌ ๋ฐ”๊พธ๊ธฐ
    ์ค‘๋ณต๋œ ์ˆ˜๊ฐ€ ์ž…๋ ฅ๊ฐ’์— ์—†์œผ๋ฉด ์ƒ๊ด€์ด ์—†๋Š”๋ฐ ์ค‘๋ณต๋œ ์ˆ˜๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ์—๋Š” ๊ฐ€์žฅ ๋ฉ€๋ฆฌ์žˆ๋Š” ์ธ๋ฑ์Šค์˜ ๊ฐ’๊ณผ ๋ฐ”๊ฟ”์•ผํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ํ•ด๋‹น ๊ฐ’์ด ๋ช‡ ๋ฒˆ ์ธ๋ฑ์Šค์— ์žˆ๋Š”์ง€ ์•Œ๊ธฐ ์œ„ํ•˜์—ฌ defaultdict์„ ์‚ฌ์šฉํ•˜์˜€๋‹ค.
    506060 ์ด ๋“ค์–ด์™”๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๋ฉด, ์ตœ์†Ÿ๊ฐ’์œผ๋กœ 500066์ด ๋‚˜์™€์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— โ€˜0โ€™์ด ์กด์žฌํ•˜๋Š” ์ธ๋ฑ์Šค ์ค‘์— ๊ฐ€์žฅ ๋ฉ€๋ฆฌ ์žˆ๋Š” ์ธ๋ฑ์Šค๋ฅผ ๊ฐ–๊ณ ์˜ค๊ธฐ์œ„ํ•˜์—ฌ index_dic[โ€˜0โ€™][-1]์„ ์‚ฌ์šฉํ•œ ๊ฒƒ์ด๋‹ค.

๐Ÿฅ‚์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from collections import defaultdict
from heapq import heappush,heappop

def Find_val(string,heap,sign):
    answer=list(string)
    for i,num in enumerate(string):
        if heap:
            val = str(heappop(heap)*sign)
            if num!=val:
                inx = index_dic[val][-1]
                answer[inx]=answer[i]
                answer[i]=val
                break
        if i==0 and index_dic['0']:
            for _ in index_dic['0']:
                heappush(heap,0)
    return ''.join(answer)

T=int(input())
for tc in range(1,T+1):
    string = input()
    min_heap, max_heap=[],[]
    index_dic=defaultdict(list)

    for inx,num in enumerate(string):
        if num !='0':
            heappush(min_heap,int(num))
            heappush(max_heap,int(num)*(-1))
        index_dic[num].append(inx)

    min_answer=Find_val(string,min_heap,1)
    max_answer=Find_val(string,max_heap,-1)
    
    print('#{} {} {}'.format(tc,min_answer,max_answer))
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.