[๋ฐฑ์ค€ ๐Ÿฅ‡4] 21940๋ฒˆ ๊ฐ€์šด๋ฐ์—์„œ ๋งŒ๋‚˜๊ธฐ (Python/ํŒŒ์ด์ฌ)

mingssoยท2023๋…„ 3์›” 20์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
26/35

1๏ธโƒฃ ๋ฌธ์ œ

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

2๏ธโƒฃ ์ฝ”๋“œ

์นœ๊ตฌ๋“ค์ด ์‚ด๊ณ  ์žˆ๋Š” ๋„์‹œ๋ฒˆํ˜ธ ๋•Œ๋ฌธ์— ํ—ท๊ฐˆ๋ ธ๋˜ ๋ฌธ์ œ

import sys

INF = sys.maxsize

n, m = map(int, sys.stdin.readline().split())
time = [[INF] * n for _ in range(n)]
for _ in range(m):
    a, b, t = map(int, sys.stdin.readline().split())
    time[a-1][b-1] = t

k = int(input())
city = list(map(int, sys.stdin.readline().split()))

def floyd():
    dist = [[INF] * n for _ in range(n)]

    for i in range(n):
        for j in range(n):
            dist[i][j] = time[i][j]

    for k in range(n):
        for i in range(n):
            for j in range(n):
                if dist[i][j] > dist[i][k] + dist[k][j]:
                    dist[i][j] = dist[i][k] + dist[k][j]

    return dist


dist = floyd()
travel = []

# ์™•๋ณต ๊ฑฐ๋ฆฌ ๊ตฌํ•˜๊ธฐ
for i in range(len(city)):
    temp = []
    for j in range(n):
        if (city[i] - 1) == j:
            temp.append(0)
        elif dist[city[i]-1][j] == INF or dist[j][city[i]-1] == INF:
            temp.append(INF)
        else:
            temp.append(dist[city[i]-1][j] + dist[j][city[i]-1])

    travel.append(temp)

answer = []
for j in range(n):
    temp = 0
    for i in range(len(city)):
        if temp < travel[i][j]:
            temp = travel[i][j]

    answer.append(temp)

ans = min(answer)
for i in range(n):
    if answer[i] == ans:
        print(i+1, end=' ')



3๏ธโƒฃ ํ’€์ด

ํ”Œ๋กœ์ด๋“œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ๋„์‹œ N๊ฐœ ์‚ฌ์ด์˜ ์ตœ๋‹จ ์‹œ๊ฐ„์„ ๊ตฌํ•ด์ค€ ๋’ค(NxN ๋ฆฌ์ŠคํŠธ)
์นœ๊ตฌ๋“ค์ด ์‚ด๊ณ  ์žˆ๋Š” ๋„์‹œ๋ฅผ ์ถœ๋ฐœ์ , N๊ฐœ์˜ ๋„์‹œ๋ฅผ ๋„์ฐฉ์ ์œผ๋กœ ํ•˜๋Š” ์™•๋ณต ์‹œ๊ฐ„์„ ๊ตฌํ•ด์ฃผ์—ˆ๋‹ค(KxN ๋ฆฌ์ŠคํŠธ)
๊ทธ๋ฆฌ๊ณ  N๊ฐœ์˜ ๋„์‹œ๋ณ„๋กœ ์™•๋ณต์‹œ๊ฐ„์˜ ์ตœ๋Œ“๊ฐ’์„ ๊ตฌํ•ด์ฃผ๊ณ  ๋‹ต์„ ๊ตฌํ–ˆ๋‹ค
โ€‹
์—ฌ๊ธฐ์„œ ๋‚ด๊ฐ€ ํ—ท๊ฐˆ๋ ธ๋˜ ๊ฒƒ์€ ์™•๋ณต์‹œ๊ฐ„์˜ ์ตœ๋Œ“๊ฐ’์„ ๊ตฌํ•ด์ฃผ๋Š” ๋ถ€๋ถ„์ด์—ˆ๋Š”๋ฐ
์นœ๊ตฌ๋“ค์ด ์‚ด๊ณ ์žˆ๋Š” ๋„์‹œ๊ฐ€ 3, 2, 1์ด๋ผ๊ณ  ํ•˜๋ฉด
3๋ฒˆ ๋„์‹œ์— ์‚ด๊ณ ์žˆ๋Š” ์นœ๊ตฌ์˜ ์™•๋ณต์‹œ๊ฐ„์€ travel ๋ฆฌ์ŠคํŠธ์˜ 0๋ฒˆ ์ธ๋ฑ์Šค์— ์žˆ์Œ!
๋„์‹œ ๋ฒˆํ˜ธ๋ฅผ ์ธ๋ฑ์Šค ๋ฒˆํ˜ธ๋กœ ์ฐฉ๊ฐํ•ด์„œ ์ธ๋ฑ์Šค ์—๋Ÿฌ๊ฐ€ ๋–ด๋‹ค

โ€‹

profile
๐Ÿฅ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ’ฐ

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