https://www.acmicpc.net/problem/1389
๋ฌธ์ ๋ฅผ ๋ณด๋ค๊ฐ ์ต๊ทผ์ ๊ณต๋ถํ ํ๋ก์ด๋ ์์ฌ๋ก ํ ์ ์์ ๊ฑฐ ๊ฐ์ ์ฌ์ฉํ๋๋ ํต๊ณผ๋๋ค.
ํ์ด ๊ณผ์
for _ in range(M):
a,b = map(int,sys.stdin.readline().rstrip().split())
graph[a][b] = 1
graph[b][a] = 1
for i in range(1, N + 1):
for j in range(1, N + 1):
if i == j:
graph[i][j] = 0
ํ๋ก์ด๋ ๋ฐฉ์์ผ๋ก ํ๋ ์๊ฐํ ๊ฑด ๊ทธ๋ํ ์์ฑ๊ณผ ๊ฐ์ค์น๋ค.
๊ทธ๋ํ์ ๊ฐ์ ์๋ฐฉํฅ์ผ๋ก ํ๊ณ ๊ฐ์ค์น๋ 1๋ก ์ค์ ํ๋ค.
for k in range(1, N + 1):
for i in range(1, N + 1):
for j in range(1 , N + 1):
graph[i][j] = min(graph[i][j],graph[i][k] + graph[k][j])
k: ์ค๊ฐ ๊ฒฝ์ ๋ ธ๋, i: ์์ ๋ ธ๋, j: ๋์ฐฉ ๋ ธ๋
ํ๋ก์ด๋ ์๊ณ ๋ฆฌ์ฆ ๋ถ๋ถ์ด๋ค. ์๊ฐ ๋ณต์ก๋ O(V^3)์ผ๋ก ์ต๋ 100*3 = 10^6์ด๋ค.
bacon = INF
answer = 0
for i in range(N, 0, -1):
s = sum(graph[i][1:])
if bacon >= s:
bacon = s
answer = i
print(answer)
๋ฌธ์ ์์ ๋ฒ ์ด์ปจ ์๊ฐ ๊ฐ์ฅ ์ ์ ์ฌ๋์ด๋ผ ํ์ผ๋ n๋ฒ์งธ ํ์ ํฉ์ด ์ ์ผ ์ ์ ์ฌ๋์ ์ฐพ์ผ๋ฉด ๋๋ค.
๊ทผ๋ฐ ๋ฒ ์ด์ปจ ์๊ฐ ๊ฐ์ฅ ์ ์ ์ฌ๋์ด ์ฌ๋ฌ ๋ช ์ด๋ฉด ๋ฒํธ๊ฐ ๊ฐ์ฅ ์์ ์ฌ๋์ ์ถ๋ ฅํ๋ผ ํ์ผ๋ฏ๋ก
for๋ฌธ์ ์ญ์์ผ๋ก ์คํํ๋ฉด ๋๋ค.
์ ์ฒด ์ฝ๋
import sys
INF = int(1e9)
N, M = map(int,input().split())
graph =[[INF] * (N + 1) for _ in range(N + 1)]
for _ in range(M):
a,b = map(int,sys.stdin.readline().rstrip().split())
graph[a][b] = 1
graph[b][a] = 1
for i in range(1, N + 1):
for j in range(1, N + 1):
if i == j:
graph[i][j] = 0
for k in range(1, N + 1):
for i in range(1, N + 1):
for j in range(1 , N + 1):
graph[i][j] = min(graph[i][j],graph[i][k] + graph[k][j])
bacon = INF
answer = 0
for i in range(N, 0, -1):
s = sum(graph[i][1:])
if bacon >= s:
bacon = s
answer = i
print(answer)
'๐งฉ Problem Solving > [๋ฐฑ์ค]' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 1107 ๋ฆฌ๋ชจ์ฝ (python ํ์ด์ฌ) (0) | 2022.06.22 |
---|---|
[๋ฐฑ์ค] 16234 ์ธ๊ตฌ์ด๋ (python ํ์ด์ฌ) (0) | 2022.06.21 |
[๋ฐฑ์ค] 7562 ๋์ดํธ์ ์ด๋ (python ํ์ด์ฌ) (0) | 2022.06.18 |
[๋ฐฑ์ค] 11404 ํ๋ก์ด๋ (python ํ์ด์ฌ) (0) | 2022.06.18 |
[๋ฐฑ์ค] 17070 ํ์ดํ ์ฎ๊ธฐ๊ธฐ 1 (python ํ์ด์ฌ) (0) | 2022.06.16 |