BOJ/๐Ÿฅˆ

โ˜…Set/Map Upper-Intermediate I - 2 Solvedโ˜…

metamong 2023. 8. 11.

โ˜… 2910 ๋นˆ๋„ ์ •๋ ฌ โ˜…

 

import sys
input=sys.stdin.readline

N,C=map(int,input().split())
freq=dict()

message=list(map(int,input().split()))

order=1
for n in message:
    if n not in freq:
        freq[n] = [1, order]
        order += 1
    else:
        freq[n][0] += 1

freq_sorted = sorted(freq.items(), key=lambda x:(-x[1][0],x[1][1]))

for x in freq_sorted:
    for _ in range(x[1][0]):
        print(str(x[0]),end=' ')

 

๐Ÿง‘๐Ÿป‍๐ŸŽจ hash table์˜ key๊ฐ’์€ ๊ณ ์œ ํ•œ ์ˆซ์ž, value๋Š” ์ˆซ์ž์˜ ๋นˆ๋„์™€ ์ˆซ์ž ์ถœํ˜„ ์ˆœ์„œ ๋‘ ๊ฐœ๋ฅผ list ํ˜•ํƒœ๋กœ ์ €์žฅํ•˜๊ฒŒ๋” ๊ตฌ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค

 

๐Ÿง‘๐Ÿป‍๐ŸŽจ ์•Œ์•„์•ผ ํ•  ๊ฒƒ โ‘ 

์•„๋ž˜ ์˜ˆ์‹œ ํ™•์ธ: ๋จผ์ € ๋นˆ๋„์ˆ˜ ๊ธฐ์ค€์— ๋งž๊ฒŒ ์ •๋ ฌ(default ์˜ค๋ฆ„์ฐจ์ˆœ์ด๋ฏ€๋กœ ์•ž์— - ๋ถ™์—ฌ ๋‚ด๋ฆผ์ฐจ์ˆœ / order ์˜ค๋ฆ„์ฐจ์ˆœ์ด๋ฏ€๋กœ ๊ทธ๋Œ€๋กœ)

โ€ป dictionary sorted() lambda function ์‚ฌ์šฉ code ๊ผญ ์ต์ˆ™ํ•ด์ง€๊ธฐ โ€ป

๐Ÿง‘๐Ÿป‍๐ŸŽจ ์•Œ์•„์•ผ ํ•  ๊ฒƒ โ‘ก

: ๋ฉ”๋ชจ๋ฆฌ ์ ˆ์•ฝ์„ ์œ„ํ•ด ์• ์ดˆ์— dictionary๋ฅผ ๋ชจ๋“  ์ž์—ฐ์ˆ˜๋กœ ์ดˆ๊ธฐํ™”ํ•˜์ง€ ๋ง๊ณ , ๋“ฑ์žฅํ•˜๋Š” ๋ถ€๋ถ„๋งŒ key๋ฅผ ๋งŒ๋“ ๋‹ค


โ˜… 20920 ์˜๋‹จ์–ด ์•”๊ธฐ๋Š” ๊ดด๋กœ์›Œ โ˜…

import sys
input=sys.stdin.readline
from collections import defaultdict

N,M=map(int,input().split())
note=defaultdict(list)
for _ in range(N):
    word=input().rstrip()
    if len(word)>=M:
        if word in note.keys():
            note[word][0]+=1
        else:
            note[word].extend([1,len(word)])
note=sorted(note.keys(),key= lambda x: (-note[x][0],-note[x][1],x))
print(*note,sep='\n')

 

๐Ÿง‘๐Ÿป‍๐ŸŽจ dictionary sorting

: defauldict๋กœ list๊ฐ€ key์ธ dictionary๋ฅผ ๋งŒ๋“ค์–ด [๋นˆ๋„์ˆ˜, ๊ธธ์ด] update. key = lambda x: ๋กœ list์˜ ์ฒซ๋ฒˆ์งธ ์š”์†Œ ๋จผ์ € → list์˜ ๋‘๋ฒˆ์งธ ์š”์†Œ → key ๊ฐ’ alphabetical order ์ •๋ ฌ code (lambda x : (-note[x][0], -note[x][1], x)) ๊ฑฐ๊พธ๋กœ ์ •๋ ฌํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ์ˆซ์ž์˜ ๊ฒฝ์šฐ ์•ž์— ๋งˆ์ด๋„ˆ์Šค ๋ถ€ํ˜ธ(-) ๋ถ™์ด๊ธฐ


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

๋Œ“๊ธ€