๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] ๋‹จ์–ด ์ •๋ ฌ BOJ #1181

by seolhee2750 2022. 2. 2.
๋ฌธ์ œ

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

 

1181๋ฒˆ: ๋‹จ์–ด ์ •๋ ฌ

์ฒซ์งธ ์ค„์— ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ N ≤ 20,000) ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ง„ ๋‹จ์–ด๊ฐ€ ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง€๋Š” ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋Š” 50์„ ๋„˜์ง€ ์•Š๋Š”๋‹ค.

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import sys

n = int(sys.stdin.readline())
result = []

for _ in range(n):
    now = sys.stdin.readline().strip()
    result.append((len(now), now))

result = list(set(result))
result.sort()

for i in range(len(result)):
    print(result[i][1])

๐Ÿ‘‰ ๋ฌธ์ž์—ด ๋ฌธ์ œ๋กœ, set๊ณผ ํŠœํ”Œ, ๊ทธ๋ฆฌ๊ณ  sort๋ฅผ ์•Œ๋งž๊ฒŒ ์‚ฌ์šฉํ•ด์ฃผ๋ฉด ๋จ

  • ์ž…๋ ฅ์ด ์•„์ฃผ ๋งŽ์ด ์žˆ์„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ input() ๋Œ€์‹  sys.stdin.readline์„ ์ด์šฉํ•ด์ฃผ์—ˆ๊ณ ,
    ์ž…๋ ฅ์„ ๋ฌธ์ž์—ด ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•  ์˜ˆ์ •์ด๋ฏ€๋กœ ๋งจ ๋’ค์— ๋ถ™์€ '\n'์„ ์‚ญ์ œํ•˜๊ธฐ ์œ„ํ•ด strip()์„ ๋ถ™์˜€๋‹ค.
  • ์ž…๋ ฅ๋ฐ›์€ ๋ฌธ์ž์—ด์€ (๋ฌธ์ž์—ด์˜ ๊ธธ์ด, ๋ฌธ์ž์—ด) ์˜ ํŠœํ”Œ ํ˜•ํƒœ๋กœ result ๋ฆฌ์ŠคํŠธ์— ๋ชจ๋‘ ์ถ”๊ฐ€ํ–ˆ๋‹ค.
  • ์™„์„ฑ๋œ result ๋ฆฌ์ŠคํŠธ๋Š” set๋กœ ๋งŒ๋“ค์–ด์„œ ์ค‘๋ณต์„ ์ œ๊ฑฐํ•˜๊ณ , ๋‹ค์‹œ list๋กœ ๋งŒ๋“ค์–ด์ฃผ์—ˆ๋‹ค.
  • sort๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ •๋ ฌํ–ˆ๋Š”๋ฐ, ์•ž์„œ ๋งํ–ˆ๋“ฏ (๋ฌธ์ž์—ด์˜ ๊ธธ์ด, ๋ฌธ์ž์—ด)์˜ ํ˜•ํƒœ๋กœ ์ €์žฅํ–ˆ๊ธฐ ๋•Œ๋ฌธ์—
    ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ ์šฐ์„ ์œผ๋กœ ์ •๋ ฌ๋˜๊ณ , ๊ธธ์ด๊ฐ€ ๊ฐ™์„ ๊ฒฝ์šฐ ๋ฌธ์ž์—ด์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ๋œ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์‰ฌ์šด ๋ฌธ์ œ์ง€๋งŒ ๋ฌธ์ž์—ด ๋ฌธ์ œ๋ฅผ ๋„ˆ๋ฌด ์˜ค๋žœ๋งŒ์— ํ’€์—ˆ๋”๋‹ˆ ์ค‘๋ณต์„ set๋กœ ์ œ๊ฑฐํ•˜๋Š” ๊ฒƒ์„ ๊นŒ๋จน์—ˆ๋‹ค.
    ๊ทธ๋ž˜์„œ ์ฒ˜์Œ์—๋Š” ์ผ์ผ์ด ๋‹ค ๋น„๊ตํ•ด์ฃผ์—ˆ๋”๋‹ˆ, ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.

๋Œ“๊ธ€