Hello Ocean! ๐ŸŒผ

[๋ฐฑ์ค€/Python] 1501. ์˜์–ด ์ฝ๊ธฐ ๋ณธ๋ฌธ

Algorithm

[๋ฐฑ์ค€/Python] 1501. ์˜์–ด ์ฝ๊ธฐ

bba_dda 2021. 10. 6. 18:40
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

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

 

1501๋ฒˆ: ์˜์–ด ์ฝ๊ธฐ

์ฒซ์งธ ์ค„์— ์‚ฌ์ „์— ์žˆ๋Š” ๋‹จ์–ด๋“ค์˜ ๊ฐœ์ˆ˜ N(0 ≤ N ≤ 10,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ ์ค„์— ํ•˜๋‚˜์”ฉ, ์˜์–ด ์‚ฌ์ „์— ์žˆ๋Š” ๋‹จ์–ด๋“ค์ด ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ๋‹จ์–ด์˜ ๊ธธ์ด๋Š” 100์ž๋ฅผ ๋„˜์ง€ ์•Š๋Š”๋‹ค. ๋‹ค์Œ ์ค„์—

www.acmicpc.net

ํ’€์ด

๋ฌธ์žฅ์„ ํ•ด์„ํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•ด์•ผ ํ•œ๋‹ค. 

๋ฌธ์žฅ์„ ๊ณต๋ฐฑ์„ ๊ธฐ์ค€์œผ๋กœ ์ž˜๋ผ์„œ ๋‹จ์–ด๋“ค๋กœ ๋งŒ๋“ค์—ˆ๋‹ค.

๊ฐ ๋‹จ์–ด๋“ค์€ ๋งจ ์•ž๊ณผ ๋งจ ๋’ท ๊ธ€์ž๋ฅผ ์ œ์™ธํ•˜๊ณ  ์ˆœ์„œ๋ฅผ ๋ฐ”๊พธ์–ด ๋‹ค์–‘ํ•œ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค. 

์ด ๊ฒฝ์šฐ์˜ ์ˆ˜ ์ค‘์— ์‚ฌ์ „์—์„œ ์ฐพ์„ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ ํ•„์š”ํ•˜๋‹ค. 

 

์ค‘๊ฐ„์— ํ—ท๊ฐˆ๋ ธ๋˜ ์ ์€, 

์–ด๋–ค  ๋ฌธ์žฅ์ด 3๊ฐœ์˜ ๋‹จ์–ด๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ๊ณ , ๊ฐ๊ฐ 2๊ฐ€์ง€, 0๊ฐ€์ง€, 3๊ฐ€์ง€๋กœ ํ•ด์„๋  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์— 

2*0*3 = 0์ด ์•„๋‹ˆ๋ผ, 0์€ ์—†๋Š” ์…ˆ ์น˜๊ณ  2*3 = 6์ด ๋‹ต์ด ๋œ๋‹ค๋Š” ๊ฒƒ์ด์—ˆ๋‹ค. 

 

์ž๋ฃŒ๊ตฌ์กฐ๋กœ dict๋ฅผ ์ด์šฉํ•˜์˜€๋Š”๋ฐ, key๋ฅผ "(๋งจ์•ž๊ธ€์ž)(๋งจ๋’ท๊ธ€์ž)(๊ฐ€์šด๋ฐ๋ฌธ์ž๋“ค์ •๋ ฌ)"๋กœ ์ด์šฉํ•˜์˜€๋‹ค. 

์˜ˆ๋ฅผ๋“ค์–ด "befakdf" ๋Š” "bfadefk"๊ฐ€ ๋œ๋‹ค. 

๋”ฐ๋ผ์„œ, ์‚ฌ์ „์— "abec"์™€ "aebc"๊ฐ€ ์žˆ๋‹ค๋ฉด ์ด ๋‘˜์˜ key๋Š” ๊ฐ™๋‹ค. 

๊ทธ๋ž˜์„œ value๋Š” ํ•ด๋‹น key๊ฐ€ ๋“ฑ์žฅํ•œ ํšŸ์ˆ˜๋ฅผ ๋„ฃ์–ด์ฃผ์—ˆ๋‹ค. 

 

์‚ฌ์ „์„ ๋ชจ๋‘ ๋งŒ๋“  ํ›„์— 

 

๋ฌธ์žฅ์— ์žˆ๋Š” ๋‹จ์–ด๋“ค์„ dict์—์„œ key๋ฅผ ๋งŒ๋“  ๋ฐฉ๋ฒ•๊ณผ ๋™์ผํ•˜๊ฒŒ ๋งŒ๋“ค์–ด์„œ, ์‚ฌ์ „์—์„œ value๋ฅผ ์กฐํšŒํ•œ ๋’ค value๊ฐ€ 0์ด ์•„๋‹ ๊ฒฝ์šฐ์—๋งŒ ๊ณฑํ•ด์ฃผ์—ˆ๋‹ค. 

 

* ์œ„์—์„œ key๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์—์„œ, 1๊ธ€์ž์™€ 2๊ธ€์ž์งœ๋ฆฌ๋Š” if๋กœ ๊ฒ€์‚ฌํ•ด์„œ ๋”ฐ๋กœ key๋ฅผ ๋งŒ๋“ค์–ด์ฃผ์—ˆ๋‹ค. 

์ฝ”๋“œ

from collections import defaultdict
dic = defaultdict(dict)

N = int(input())
for i in range(N):
    word = input()
    if (len(word) <= 2):
        try : dic[word]['']+=1
        except : dic[word]['']=1
    else:
        first_k = word[0]+word[-1]
        sec_k = str(sorted(word[1:-1]))
        try : dic[first_k][sec_k]+=1
        except : dic[first_k][sec_k]=1
        
M = int(input())
for i in range(M):
    sen = input().split(' ')
    count = 1
    isCan = False
    for idx, w in enumerate(sen):
        temp = 0
        if (len(w) <= 2):
            try :temp += dic[w]['']
            except: temp
        else:
            start = w[0]
            end = w[-1]
            middle = str(sorted(w[1:-1]))
            try: temp+= dic[start+end][middle]
            except: temp
        if temp != 0:
            count*=temp
            isCan = True
    if not isCan:
        count = 0
    print(count)

python์œผ๋กœ ์–ด๋ ค์šด ๋ฌธ์ œ๋ฅผ ํ‘ธ๋Š” ๊ฒƒ์ด ์ฒ˜์Œ์ด๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ตฌํ˜„ํ•˜๋Š” ๋ถ€๋ถ„์„ ๊ต‰์žฅํžˆ ํ—ค๋งธ๋‹ค. 

๊ฒฐ๊ณผ

๋ฐ˜์‘ํ˜•