Search

๊ทธ๋ž˜ํ”„ ๊ตฌํ˜„

Created At
2022/02/03 02:35
Updated At
2022/03/13 17:08
๋ถ„๋ฅ˜
์ž๋ฃŒ๊ตฌ์กฐ
๊ทธ๋ž˜ํ”„
โ€ข
๋ฐฉํ–ฅ์—ฌ๋ถ€ : ๋ฌดํ–ฅ๊ทธ๋ž˜ํ”„(์–‘๋ฐฉํ–ฅ) vs ์œ ํ–ฅ๊ทธ๋ž˜ํ”„(๋‹จ๋ฐฉํ–ฅ)
โ€ข
๊ฐ€์ค‘์น˜์—ฌ๋ถ€ : ๋น„๊ฐ€์ค‘์น˜๊ทธ๋ž˜ํ”„ vs ๊ฐ€์ค‘์น˜๊ทธ๋ž˜ํ”„
ํŒŒ์ด์ฌ์— ๊ทธ๋ž˜ํ”„ ๊ตฌํ˜„ ๋ฐฉ๋ฒ•
1.
n*n ๋ฐฐ์—ด(์ธ์ ‘ํ–‰๋ ฌ)
2.
๋”•์…”๋„ˆ๋ฆฌ or ๋ฐฐ์—ด(์ธ์ ‘๋ฆฌ์ŠคํŠธ)
์ด ๋ฌธ์ œ๋Š” ๊ฐ€์ค‘์น˜ ๋‹จ๋ฐฉํ–ฅ๊ทธ๋ž˜ํ”„์ด๋‹ค.
Code

์ธ์ ‘ํ–‰๋ ฌ

n, m = map(int, input().split()) graph = [[0] * (n + 1) for _ in range(n + 1)] for _ in range(m): i, j, w = map(int, input().split()) # ์‹œ์ž‘,๋„์ฐฉ,๊ฐ€์ค‘์น˜ graph[i][j] = w for i in range(1, n + 1): for j in range(1, n + 1): print(graph[i][j], end=" ") print() """ 6 9 1 2 7 1 3 4 2 1 2 2 3 5 2 5 5 3 4 5 4 2 2 4 5 5 6 4 5 """ 0 7 4 0 0 0 2 0 5 0 5 0 0 0 0 5 0 0 0 2 0 0 5 0 0 0 0 0 0 0 0 0 0 5 0 0
Python
๋ณต์‚ฌ

์ธ์ ‘๋ฆฌ์ŠคํŠธ(๋ฐฐ์—ด)

# ์ธ์ ‘๋ฆฌ์ŠคํŠธ ๋ฐฉ์‹ (๋ฐฐ์—ด์‚ฌ์šฉ) n, m = map(int, input().split()) graph = [[] for _ in range(n + 1)] for _ in range(m): i, j, w = map(int, input().split()) graph[i].append((j, w)) # (j,w) == (๋„์ฐฉ๋…ธ๋“œ, ๊ฐ€์ค‘์น˜) for i in range(len(graph)): print(f"{i} : {graph[i]}") """ 6 9 1 2 7 1 3 4 2 1 2 2 3 5 2 5 5 3 4 5 4 2 2 4 5 5 6 4 5 """ 0 : [] 1 : [(2, 7), (3, 4)] 2 : [(1, 2), (3, 5), (5, 5)] 3 : [(4, 5)] 4 : [(2, 2), (5, 5)] 5 : [] 6 : [(4, 5)]
Python
๋ณต์‚ฌ

์ธ์ ‘๋ฆฌ์ŠคํŠธ(๋”•์…”๋„ˆ๋ฆฌ)

์ œ์ผ ์ข‹์€ ๋ฐฉ์‹

# ์ธ์ ‘๋ฆฌ์ŠคํŠธ ๋ฐฉ์‹ (๋”•์…”๋„ˆ๋ฆฌ์‚ฌ์šฉ) n, m = map(int, input().split()) graph = {} # ๋…ธ๋“œ๊ฐ’์œผ๋กœ ๋”•์…”๋„ˆ๋ฆฌ์— key ์ƒ์„ฑ for i in range(1, n + 1): # 1๋ฒˆ๋…ธ๋“œ๋ถ€ํ„ฐ n๋ฒˆ๊นŒ์ง€๋กœ ํ•ด์•ผํ•˜๋ฏ€๋กœ graph[i] = [] # ๊ทธ๋ž˜ํ”„ ์ƒ์„ฑ for _ in range(m): i, j, w = map(int, input().split()) graph[i].append((j, w)) # i : ์‹œ์ž‘๋…ธ๋“œ, j : ๋„์ฐฉ๋…ธ๋“œ, w : ๊ฐ€์ค‘์น˜ # graph[i] += [(j, w)] # ๋˜‘๊ฐ™์€ ์ฝ”๋“œ for i in graph.keys(): print(f"{i} : {graph[i]}") """ 6 9 1 2 7 1 3 4 2 1 2 2 3 5 2 5 5 3 4 5 4 2 2 4 5 5 6 4 5 """ 1 : [(2, 7), (3, 4)] 2 : [(1, 2), (3, 5), (5, 5)] 3 : [(4, 5)] 4 : [(2, 2), (5, 5)] 5 : [] 6 : [(4, 5)]
Python
๋ณต์‚ฌ
ย ์ด ๋ฐฉ์‹์ด ์ œ์ผ ์ข‹์€ ์ด์œ ๋Š” ์ธ์ ‘๋…ธ๋“œ๊ฐ€ ์—†๋Š” ๋…ธ๋“œ๋„ ์ƒ์„ฑ์„ ํ•ด์ค€๋‹ค. (5๋ฒˆ๋…ธ๋“œ)

๋น„์ถ”์ฒœ

# ์ธ์ ‘๋ฆฌ์ŠคํŠธ ๋ฐฉ์‹ 2 (๋”•์…”๋„ˆ๋ฆฌ์‚ฌ์šฉ) n, m = map(int, input().split()) graph = {} for _ in range(m): i, j, w = map(int, input().split()) graph[i] = graph.get(i, []) + [(j, w)] # append((j,w)) ๋กœ ํ•˜๋ฉด ์•ˆ๋จ! append ์˜ ๋ฆฌํ„ด์€ None ์ด๋ฏ€๋กœ # (j,w) == (๋„์ฐฉ๋…ธ๋“œ, ๊ฐ€์ค‘์น˜) for i in graph.keys(): print(f"{i} : {graph[i]}") """ 6 9 1 2 7 1 3 4 2 1 2 2 3 5 2 5 5 3 4 5 4 2 2 4 5 5 6 4 5 """ 1 : [(2, 7), (3, 4)] 2 : [(1, 2), (3, 5), (5, 5)] 3 : [(4, 5)] 4 : [(2, 2), (5, 5)] 6 : [(4, 5)]
Python
๋ณต์‚ฌ
ย ๋˜‘๊ฐ™์ด ๋”•์…”๋„ˆ๋ฆฌ๋กœ ๊ตฌํ˜„์„ ํ–ˆ์ง€๋งŒ get() ํ•จ์ˆ˜๋ฅผ ์จ์•ผํ•˜๊ณ , ์ธ์ ‘๋…ธ๋“œ๊ฐ€ ์—†๋Š” ๋…ธ๋“œ (5๋ฒˆ๋…ธ๋“œ) ๋Š” ์•„์˜ˆ ์ƒ์„ฑ์ด ์•ˆ๋œ ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค. ๊ฐ„ํ˜น ์ด๊ฒƒ๋•Œ๋ฌธ์— ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค˜์•ผํ•  ๋•Œ๊ฐ€ ์žˆ์–ด์„œ ๊ทธ๋ƒฅ 1๋ฒˆ ๋”•์…”๋„ˆ๋ฆฌ ๋ฐฉ์‹์ด ๋” ํŽธํ•˜๋‹ค.