๐ŸŒฑ → ๐ŸŒณ

[๋ฐฑ์ค€] 18870๋ฒˆ: ์ขŒํ‘œ ์••์ถ• python ๋ณธ๋ฌธ

Algorithms

[๋ฐฑ์ค€] 18870๋ฒˆ: ์ขŒํ‘œ ์••์ถ• python

BAY 2022. 10. 10. 10:44
728x90

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

 

18870๋ฒˆ: ์ขŒํ‘œ ์••์ถ•

์ˆ˜์ง์„  ์œ„์— N๊ฐœ์˜ ์ขŒํ‘œ X1, X2, ..., XN์ด ์žˆ๋‹ค. ์ด ์ขŒํ‘œ์— ์ขŒํ‘œ ์••์ถ•์„ ์ ์šฉํ•˜๋ ค๊ณ  ํ•œ๋‹ค. Xi๋ฅผ ์ขŒํ‘œ ์••์ถ•ํ•œ ๊ฒฐ๊ณผ X'i์˜ ๊ฐ’์€ Xi > Xj๋ฅผ ๋งŒ์กฑํ•˜๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ์ขŒํ‘œ์˜ ๊ฐœ์ˆ˜์™€ ๊ฐ™์•„์•ผ ํ•œ๋‹ค. X1, X2, ..., XN์— ์ขŒ

www.acmicpc.net

๐Ÿ“Œ  ๋ฌธ์ œ ํ•ด์„ค

"Xi>Xj๋ฅผ ๋งŒ์กฑํ•˜๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ์ขŒํ‘œ์˜ ๊ฐœ์ˆ˜์™€ ๊ฐ™์•„์•ผ๋œ๋‹ค" ๋ผ๋Š” ๋œป์€ ์ฆ‰ Xi๊ฐ€ ๋ฆฌ์ŠคํŠธ ์•ˆ์—์„œ์˜ ํฌ๊ธฐ ์ˆœ์„œ๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค๋Š” ๋ง

(ํฌ๊ธฐ ์ˆœ์„œ๋Š” 0๋ถ€ํ„ฐ ์‹œ์ž‘.)

์ฆ‰, ๋ฆฌ์ŠคํŠธ์•ˆ์—์„œ ์ž๊ธฐ๋ณด๋‹ค ์ž‘์€ ์ˆซ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๋Š” ๊ฒƒ์ด๋ฏ€๋กœ, ์ž์‹ ์ด ๋ฆฌ์ŠคํŠธ ์•ˆ์—์„œ์˜ ํฌ๊ธฐ ์ˆœ์„œ๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋จ

 

๐Ÿ“Œ  ์ฝ”๋“œ

์‹คํŒจ ์ฝ”๋“œ (์‹œ๊ฐ„ ์ดˆ๊ณผ)

n = int(input())
arr = list(map(int, input().split()))

arr2 = sorted(list(set(arr)))

for i in arr:
    print(arr2.index(i), end = ' ')

list.index(i) → ์‹œ๊ฐ„ ๋ณต์žก๋„ O(n)

 

์„ฑ๊ณต ์ฝ”๋“œ

n = int(input())
arr = list(map(int, input().split()))

arr2 = sorted(list(set(arr)))

dic = {arr2[i]: i for i in range(len(arr2))}

for i in arr:
  print(dic[i], end=' ')

index[i] → ์‹œ๊ฐ„ ๋ณต์žก๋„ O(1)

 

โœ”๏ธ ์ž์„ธํžˆ ์•Œ์•„๋ณด์ž) arr2, dic๋„ print ํ•ด์„œ ํ™•์ธํ•ด๋ณด๊ธฐ

n = int(input())
arr = list(map(int, input().split()))

arr2 = sorted(list(set(arr)))
print(arr2)

dic = {arr2[i]: i for i in range(len(arr2))}
print(dic)

for i in arr:
  print(dic[i], end=' ')

๊ฒฐ๊ณผ

 

๐Ÿ“ ๊ฒฐ๋ก 

list.index(i) ํ˜•ํƒœ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„ = O(N)

index[i] ํ˜•ํƒœ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„ = O(1)

 

๐Ÿ“Œ ํŒŒ์ด์ฌ ๋”•์…”๋„ˆ๋ฆฌ์— ๊ด€ํ•ด์„œ..

  1. ๋”•์…”๋„ˆ๋ฆฌ์ด๋ฆ„ = {"key๊ฐ’" : "value๊ฐ’"}
  2. key ์ค‘๋ณต ํ—ˆ์šฉ X
  3. key๊ฐ€ ์ค‘๋ณต ๋  ๊ฒฝ์šฐ ๋งˆ์ง€๋ง‰์— ์ž…๋ ฅ๋œ key์˜ value๋ฅผ ์ถœ๋ ฅ.

 

1๋ฒˆ ์˜ˆ์ œ)

dic = {"key1":"value1", "key2":"value2", "key3":"value3", "key4":"value4",}

print(dic["key1"]

#๊ฒฐ๊ณผ
# value1

 

2๋ฒˆ ์˜ˆ์ œ)

arr = [1, 0, 2, -4, 6, 33, 22]

dic = {arr[i]:i for i in range (len(arr))}

print("dic =",dic)
print("dic[33] = ",dic[33])

# ์ถœ๋ ฅ๊ฒฐ๊ณผ
# dic = {1: 0, 0: 1, 2: 2, -4: 3, 6: 4, 33: 5, 22: 6}
# dic[33] =  5

์ฐธ๊ณ ํ•œ ๋ธ”๋กœ๊ทธ :

https://eunhee-programming.tistory.com/116

[์ฝ”๋“œ์งœ๋Š” ๋ฌธ๊ณผ๋…€:ํ‹ฐ์Šคํ† ๋ฆฌ]

 

728x90