본문 바로가기
Algorithm/백준

[Python/Java] 백준 1753번 - 최단경로 (골드 4)

by 애기 개발자 2023. 10. 12.
반응형
혼자 힘으로 풀었는가? X

알고리즘 분류
 - 데이크스트라(다익스트라)
 - 최단 경로
 - 그래프 이론

 

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

 

1753번: 최단경로

첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가

www.acmicpc.net

 

문제

방향그래프가 주어지면 주어진 시작점에서 다른 모든 정점으로의 최단 경로를 구하는 프로그램을 작성하시오. 단, 모든 간선의 가중치는 10 이하의 자연수이다.

입력

첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가 주어진다. 셋째 줄부터 E개의 줄에 걸쳐 각 간선을 나타내는 세 개의 정수 (u, v, w)가 순서대로 주어진다. 이는 u에서 v로 가는 가중치 w인 간선이 존재한다는 뜻이다. u와 v는 서로 다르며 w는 10 이하의 자연수이다. 서로 다른 두 정점 사이에 여러 개의 간선이 존재할 수도 있음에 유의한다.

출력

첫째 줄부터 V개의 줄에 걸쳐, i번째 줄에 i번 정점으로의 최단 경로의 경로값을 출력한다. 시작점 자신은 0으로 출력하고, 경로가 존재하지 않는 경우에는 INF를 출력하면 된다.

 


 

기본적인 다익스트라 문제였다.

 

난 방법을 까먹어서 옛날 내 글을 다시 참조했다.

 

2022.11.15 - [Algorithm/이것이 코딩테스트다] - [Python][이코테] 최단경로 / 다익스트라 알고리즘(2)

 

[Python][이코테] 최단경로 / 다익스트라 알고리즘(2)

2022.11.09 - [Algorithm/이것이 코딩테스트다] - [Python][이코테] 최단경로 / 다익스트라 알고리즘(1) 개선된 다익스트라 알고리즘 기존의 간단한 다익스트라 알고리즘은 시간 복잡도가 \(O(V^2)\) 이다. 이

baby-dev.tistory.com

 

위와 거의 똑같다.

 

Python 코드

import sys
input = sys.stdin.readline

import heapq

v, e = map(int, input().split())
first = int(input())
graph = [ [] for i in range(v+1)]

INF = int(1e9)
distance = [INF] * (v+1)

for i in range(e):
    start, end, value = map(int, input().split())
    graph[start].append((end, value))
    
def dijkstra(start):
    q = []
    heapq.heappush(q, (0, start))
    distance[start] = 0
    
    while q:
        dist, now = heapq.heappop(q)
        
        if distance[now] < dist:
            continue
        for i in graph[now]:
            cost = dist + i[1]
            if cost < distance[i[0]]:
                distance[i[0]] = cost
                heapq.heappush(q, (cost, i[0]))

dijkstra(first)
for i in range(1, v+1):
    if distance[i] == INF:
        print("INF")
    else:
        print(distance[i])

 

Java코드

import java.io.*;
import java.util.*;

public class Main {
	static int v, e, first;
	static int INF = 100000000;
	static List<Node>[] graph;
	static int [] distance;
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		v = Integer.parseInt(st.nextToken());
		e = Integer.parseInt(st.nextToken());
		
		first = Integer.parseInt(br.readLine());
		
		graph = new ArrayList[v+1];
		distance = new int[v+1];
		
		for(int i=1; i<=v; i++) {
			distance[i] = INF;
			graph[i] = new ArrayList<>();
		}
		
		for(int i=0; i<e; i++) {
			st = new StringTokenizer(br.readLine());
			int start = Integer.parseInt(st.nextToken());
			int end = Integer.parseInt(st.nextToken());
			int value = Integer.parseInt(st.nextToken());
			
			graph[start].add(new Node(end, value));
		}
		
		dijkstra(first);
		
		for(int i=1; i<= v; i++) {
			if(distance[i] == INF) {
				System.out.println("INF");
			} else {
				System.out.println(distance[i]);
			}
		}
	}
	private static void dijkstra(int start) {
		PriorityQueue<Node> q = new PriorityQueue<Node>();
		q.add(new Node(start, 0));
		distance[start] = 0;
		
		while(!q.isEmpty()) {
			Node curNode = q.poll();
			int cur = curNode.end;
			int dist = curNode.value;
			if (distance[cur] < dist) {
				continue;
			}
			
			for(Node node : graph[cur]) {
				int cost = dist + node.value;
				if(cost < distance[node.end]) {
					distance[node.end]= cost;
					q.add(new Node(node.end, cost));
				}
			}
		}
	}
}

class Node implements Comparable<Node> {
	int end, value;
	public Node(int end, int value) {
		this.end = end;
		this.value = value;
	}
	
	@Override
	public int compareTo(Node o) {
		return value - o.value;
	}
}

 

파이썬은 힙큐를

자바는 우선순위 큐를 사용하여 풀었다.

 

자바는 너무 어렵다..

반응형

댓글