[Algorithm] ๐Ÿšฉ[๋ฐฑ์ค€] 1225 (Feat. ์‹œ๊ฐ„๋ณต์žก๋„)

myeonjiยท2022๋…„ 2์›” 4์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
29/89
post-custom-banner
a, b = map(str, input().split())

sum = 0
for i in a:
    for j in b:
        sum += int(i)*int(j)

print(sum)

์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋œฌ๋‹ค.. A, B๊ฐ€ 10,000 ์ž๋ฆฌ๋ฅผ ๋„˜์ง€ ์•Š๋Š”๋‹ค๋Š” ์กฐ๊ฑด์ด ์žˆ๊ณ , ๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ์ฝ”๋“œ๋Š” ๊ฐ€์žฅ ์˜ค๋ž˜ ๊ฑธ๋ฆฌ๋Š” ๊ฒฝ์šฐ 100,000,000 ์ด๋‹ค. ๊ทธ๋Ÿผ O(N^2) ์ด๋ผ์„œ ๋  ์ค„ ์•Œ์•˜๋Š”๋ฐ.. ์ฐพ์•„๋ณด๋‹ˆ ํŒŒ์ด์ฌ์ด ๋Š๋ฆฐ ํŽธ์ด๋ผ ์˜ˆ์ธก์„ ๋ฒ—์–ด๋‚˜ ์‹œ๊ฐ„ ๋‚ด์— ์•ˆ ๋Œ์•„๊ฐ€๋Š” ๊ฒฝ์šฐ๋„ ์žˆ๋‹ค๊ณ  ํ•œ๋‹ค.

์ž…๋ ฅ์˜ ํฌ๊ธฐ๋ฅผ ์‹œ๊ฐ„ ๋ณต์žก๋„์— ๋Œ€์ž…ํ•ด์„œ ์–ป์€ ๋ฐ˜๋ณต๋ฌธ ์ˆ˜ํ–‰ ํšŸ์ˆ˜์— ๋Œ€ํ•ด, 1์ดˆ ๋‹น ๋ฐ˜๋ณต๋ฌธ ์ˆ˜ํ–‰ ํšŸ์ˆ˜๊ฐ€ 1์–ต(10810^8)์„ ๋„˜์–ด๊ฐ€๋ฉด ์‹œ๊ฐ„ ์ œํ•œ์„ ์ดˆ๊ณผํ•  ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋‹ค.

pypy3๋กœ ์ œ์ถœํ•˜๋ฉด ๋œ๋‹ค๊ณ  ํ•˜์ง€๋งŒ ๊ทธ๋ƒฅ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ์ค„์—ฌ์„œ ํ’€์–ด๋ด์•ผ๊ฒ ๋‹ค.
์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ O(N^2)์—์„œ O(N)๋กœ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค!

a, b = map(str, input().split())

atmp = 0
btmp = 0

for i in a:
    atmp += int(i)
for j in b:
    btmp += int(j)

print(atmp*btmp)

n๋ฒˆ๋งŒํผ ๋ฐ˜๋ณตํ•˜๋Š” ๋ฐ˜๋ณต๋ฌธ์ด 2๊ฐœ์ด๋‹ค. ์ด๊ฒƒ์€ O(N^2)๊ฐ€ ์•„๋‹Œ O(N)์ด๋‹ค!
O(N)์€ ๋ฐ˜๋ณต๋ฌธ์ด ํ•˜๋‚˜๊ฐ€ ์žˆ์œผ๋‚˜ ์ˆ˜์‹ญ๊ฐœ๊ฐ€ ์žˆ์œผ๋‚˜ O(N)์ธ ๊ฒƒ์„ ๋ช…์‹ฌํ•˜์ž.

<์ฐธ๊ณ >
https://coding-factory.tistory.com/608

profile
DBA, ๊ฒฝ์ œ ๊ทธ๋ฆฌ๊ณ  ๊ณ ๋ƒฅ์ด
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€