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

[Python Algorithm] ๋ฒ ์ŠคํŠธ์…€๋Ÿฌ BOJ #1302

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

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

 

1302๋ฒˆ: ๋ฒ ์ŠคํŠธ์…€๋Ÿฌ

์ฒซ์งธ ์ค„์— ์˜ค๋Š˜ ํ•˜๋ฃจ ๋™์•ˆ ํŒ”๋ฆฐ ์ฑ…์˜ ๊ฐœ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. ์ด ๊ฐ’์€ 1,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜์ด๋‹ค. ๋‘˜์งธ๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์— ์ฑ…์˜ ์ œ๋ชฉ์ด ์ž…๋ ฅ์œผ๋กœ ๋“ค์–ด์˜จ๋‹ค. ์ฑ…์˜ ์ œ๋ชฉ์˜ ๊ธธ์ด๋Š” 50๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๊ณ 

www.acmicpc.net

 

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

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

for _ in range(n):
    now = sys.stdin.readline().strip()
    if now in books:
        count[books.index(now)][1] += 1
    else:
        books.append(now)
        count.append([len(books)-1, 1])

count.sort(key = lambda x: x[1], reverse = True)

for i in range(len(count)):
    if count[i][1] == count[0][1]:
        result.append(books[count[i][0]])
    else:
        break

result.sort()
print(result[0])

๐Ÿ‘‰ ๋ฌธ์ž์—ด ๋ฌธ์ œ๋กœ, ํŒ”๋ฆฐ ์ฑ…์˜ ๋ฆฌ์ŠคํŠธ์™€ ์ฑ…๋งˆ๋‹ค ๋ช‡ ๊ถŒ ํŒ”๋ ธ๋Š”์ง€ ์ €์žฅํ•˜๋Š” ๋ฆฌ์ŠคํŠธ๋ฅผ ๋”ฐ๋กœ ์ƒ์„ฑํ•ด์„œ ํ’€์—ˆ๋‹ค.

  • ์ž…๋ ฅ๋ฐ›์€ ์ฑ…์ด books ๋ฆฌ์ŠคํŠธ์— ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ณ ,
    ์—†๋‹ค๋ฉด books ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€ํ•œ ํ›„, count์— [ํ•ด๋‹น ์ฑ…์ด ์ €์žฅ๋œ books ์ธ๋ฑ์Šค, ๊ถŒ ์ˆ˜]๋ฅผ ์ถ”๊ฐ€ํ–ˆ๋‹ค.
    ์žˆ์„ ๋•Œ๋Š” books ๋ฆฌ์ŠคํŠธ์˜ ๋ช‡ ๋ฒˆ์งธ ์ธ๋ฑ์Šค์— ์žˆ๋Š”์ง€ ํ™•์ธํ•˜์—ฌ count ๋ฆฌ์ŠคํŠธ๋ฅผ ์—…๋ฐ์ดํŠธํ–ˆ๋‹ค.
  • ์นด์šดํŒ…์ด ๋๋‚˜๋ฉด count ๋ฆฌ์ŠคํŠธ๋ฅผ ๊ถŒ ์ˆ˜๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•˜๊ณ ,
    ์ œ์ผ ๋งŽ์ด ํŒ”๋ฆฐ ์ฑ…๋“ค์„ result ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€ํ•ด์ฃผ์—ˆ๋‹ค.
    ๊ทธ๋ฆฌ๊ณ  result๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•˜์—ฌ ๋งจ ์•ž์˜ ์ฑ…๋งŒ ์ถœ๋ ฅํ•˜๊ฒŒ ํ–ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์–ด๋ ค์šด ๋ฌธ์ œ๋Š” ์•„๋‹ˆ์—ˆ์ง€๋งŒ, ํŠœํ”Œ์ด ์ˆ˜์ • ๋ถˆ๊ฐ€ํ•˜๋‹ค๋Š” ๊ฒƒ์„ ๋ชจ๋ฅด๊ณ  ์žˆ์–ด์„œ,, ๊ทธ ๋ถ€๋ถ„์—์„œ ํ—ท๊ฐˆ๋ ธ๋‹ค.
    ํŠœํ”Œ์€ ์ˆ˜์ • ๋ถˆ๊ฐ€ํ•˜๋ฏ€๋กœ, ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“ค์–ด์„œ ์—ฐ์‚ฐ์„ ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.
  • ๊ทธ๋ฆฌ๊ณ  ๋ฆฌ์ŠคํŠธ์—์„œ ์–ด๋–ค ์š”์†Œ์˜ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ์œผ๋ ค๋ฉด ๋ฆฌ์ŠคํŠธ๋ช….index(์š”์†Œ) ์ด๋ ‡๊ฒŒ ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ๋„,,!

๋Œ“๊ธ€