정구리의 우주정복

[BOJ] 백준 13424-비밀모임 파이썬 다익스트라 본문

ALGORITHM/SOLVE

[BOJ] 백준 13424-비밀모임 파이썬 다익스트라

Jungry_ 2021. 2. 6. 00:40
반응형

www.acmicpc.net/problem/13424

 

13424번: 비밀 모임

입력 데이터는 표준 입력을 사용한다. 입력은 T개의 테스트 데이터로 구성된다. 입력의 첫 번째 줄에 테스트 케이스의 개수를 나타내는 자연수 T가 주어진다. 각 테스트 케이스의 첫째 줄에는 방

www.acmicpc.net

 

다익스트라 문제 ! 사실 플로이드 와 ~ 샬로도 풀수있지만 나는 플로이드 와 ~~샬 하는법 몰라서 그냥 다익스트라로 풀었다

 

import sys
import heapq
INF = int(1e9)
input = sys.stdin.readline

def die(start):
    q = []
    heapq.heappush(q,(0,start))
    distence[start] = 0

    while q:
        dist,now = heapq.heappop(q)
        if dist > distence[now]:
            continue
        for i in graph[now]:
            cost = dist + i[1]
            if cost < distence[i[0]]:
                distence[i[0]] = cost
                heapq.heappush(q,(cost,i[0]))
            
tc = int(input())
for _ in range(tc):
    n,m = map(int,input().split())
    graph = [[] for _ in range(n+1)]
    total_dis = [0] * (n+1)
    for _ in range(m):
        a,b,c = map(int,input().split())
        graph[a].append((b,c))
        graph[b].append((a,c))
    num = int(input())
    people = list(map(int,input().split())) #사람 어디있는지 
    for i in people:
        distence = [INF] * (n+1)
        die(i)
        for j in range(1,n+1):
            total_dis[j] += distence[j]
    minn = 0
    noww = INF
    for i in range(1,n+1):
        if noww > total_dis[i]:
            noww = total_dis[i]
            minn = i
    print(minn)

기본 다익스트라 알고리즘 사용한뒤 사람의 위치마다 다익스트라를 써준다

total_dis 라는 변수를 만들어서 여기에 각 사람마다의 거리들의 누적치를 기록해준뒤

누가누가 제일 작나 해주면 끝 !! 

 

 

반응형
Comments