๋ฐฑ์ค€ 1213 ํŒฐ๋ฆฐ๋“œ๋กฌ ๋งŒ๋“ค๊ธฐ ํŒŒ์ด์ฌ

2022. 7. 5. 00:09ใ†๐Ÿ”ฑ Algorithm/Greedy

https://www.acmicpc.net/problem/1213

 

1213๋ฒˆ: ํŒฐ๋ฆฐ๋“œ๋กฌ ๋งŒ๋“ค๊ธฐ

์ฒซ์งธ ์ค„์— ๋ฌธ์ œ์˜ ์ •๋‹ต์„ ์ถœ๋ ฅํ•œ๋‹ค. ๋งŒ์•ฝ ๋ถˆ๊ฐ€๋Šฅํ•  ๋•Œ๋Š” "I'm Sorry Hansoo"๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. ์ •๋‹ต์ด ์—ฌ๋Ÿฌ ๊ฐœ์ผ ๊ฒฝ์šฐ์—๋Š” ์‚ฌ์ „์ˆœ์œผ๋กœ ์•ž์„œ๋Š” ๊ฒƒ์„ ์ถœ๋ ฅํ•œ๋‹ค.

www.acmicpc.net

ํ’€์ด 

ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์กฐ๊ฑด์„ ์šฐ์„  ์ƒ๊ฐํ•ด๋ณด๋ฉด ๋œ๋‹ค. 

๊ฐ๊ฐ์˜ ์•ŒํŒŒ๋ฒณ์ด ์ง์ˆ˜๋กœ ๋“ฑ์žฅํ•˜๊ฑฐ๋‚˜, ํ™€์ˆ˜ ๊ฐœ์ธ ์•ŒํŒŒ๋ฒณ์ด ํ•˜๋‚˜ ์ดํ•˜๋กœ๋งŒ ์กด์žฌํ•˜๋ฉด ๋œ๋‹ค.

ํŒฐ๋ฆฐ๋“œ๋กฌ์€ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ ์ง์ˆ˜์ผ ๋•Œ,  ์ ˆ๋ฐ˜์œผ๋กœ ์ชผ๊ฐ  ์•ž์ชฝ์˜ ๋ฌธ์ž์—ด์„ reversing ํ•˜์—ฌ ๋’ท์ชฝ์˜ ๋ฌธ์ž์—ด์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

๋ฌธ์ž์—ด ๊ธธ์ด๊ฐ€ ํ™€์ˆ˜๋ผ๋ฉด, ๊ฐ€์šด๋ฐ์˜ ๋‹จ์–ด๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์•ž๋’ค๊ฐ€ ์—ญ์ˆœ์ธ ๋ฌธ์ž์—ด๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.

๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ์•ž์ชฝ ๋ฌธ์ž์—ด์— ๋ฌด์—‡์ด ๋‚˜์˜ฌ์ง€๋งŒ ํŒŒ์•…ํ•˜๋ฉด, ๋’ท์ชฝ ๋ฌธ์ž์—ด์€ ์ž๋™์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค. 

 

์ฝ”๋“œ

import sys
from collections import Counter

input = sys.stdin.readline

word = input().rstrip()
word_dict = Counter(word)
word_part, center = [], ''

if len(list(filter(lambda x: x % 2 != 0, word_dict.values()))) > 1:
    print("I'm Sorry Hansoo")
    exit()

for k, v, in word_dict.items():
    if v % 2 != 0:
        word_part += ([k] * ((v - 1) // 2))
        center = k
    else:
        word_part += ([k] * (v // 2))

front = ''.join(sorted(word_part))

print(front + center + front[::-1])

๋ฌธ์žฅ์— ๋‚˜์˜ค๋Š” ๊ฐ ์•ŒํŒŒ๋ฒณ์˜ ๊ฐฏ์ˆ˜๋ฅผ ์„ธ์•ผํ•œ๋‹ค. dictionary.get() ์„ ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ์ง€๋งŒ, collection ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์˜ Counter() ๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค. 

word_dict = Counter(word)

 

์•„์ž„ ์˜๋ฆฌ ํ•œ์ˆ˜ ๊ฐ€ ์ถœ๋ ฅ๋  ์กฐ๊ฑด์„ ๋จผ์ € ์ƒ๊ฐํ•ด๋ณด์ž.

์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด๋กœ ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ๋งŒ๋“ค์ง€ ๋ชปํ•˜๋Š” ๊ฒฝ์šฐ์ธ๋ฐ, ๋ฐ”๋กœ ํ™€์ˆ˜ ๊ฐฏ์ˆ˜์ธ ์•ŒํŒŒ๋ฒณ์ด 2๊ฐœ์ด์ƒ ๋“ฑ์žฅํ•  ๋•Œ๋‹ค.

2๊ฐœ ์ด์ƒ์˜ ํ™€์ˆ˜ ๊ฐฏ์ˆ˜์˜ ์•ŒํŒŒ๋ฒณ์ด ๋‚˜์˜ค๋ฉด ๋ฐ”๋กœ ํ”„๋กœ๊ทธ๋žจ์„ ์ข…๋ฃŒ์‹œํ‚ค๋ฉด ๋œ๋‹ค. filter() ๋‚ด๋ถ€์— ๋žŒ๋‹ค์‹์„ ์‚ฌ์šฉํ•ด ๋กœ์ง ๊ตฌํ˜„ํ–ˆ๋‹ค.

if len(list(filter(lambda x: x % 2 != 0, word_dict.values()))) > 1:
    print("I'm Sorry Hansoo")
    exit()