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
문제
풀이
nlogn 시간복잡도인 우선순위큐를 이용한 다익스트라 기본 풀이다.
간선의 가중치 낮은 순으로 우선순위큐에 들어가기때문에 n^2 방식인 최소비용탐색하는 시간이 들지 않기때문
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
import java.util.*;
import java.io.*;
public class Main{
static int MAX_DIST = 98765321;
static int[] dist;
static int V,E,start;
static ArrayList<Node>[] list;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
V = Integer.parseInt(input[0]); E = Integer.parseInt(input[1]); start = Integer.parseInt(br.readLine());
dist = new int[V+1];
Arrays.fill(dist,MAX_DIST);
list = new ArrayList[V+1];
for(int i=1;i<=V;i++)
list[i] = new ArrayList<Node>();
for(int i=1;i<=E;i++){
input = br.readLine().split(" ");
list[Integer.parseInt(input[0])].add(new Node(Integer.parseInt(input[1]),Integer.parseInt(input[2])));
}
findShortPath(start);
}
static void findShortPath(int start) {
PriorityQueue<Node> q = new PriorityQueue<>();
q.add(new Node(start,0));
dist[start] = 0;
while (!q.isEmpty()){
Node poll = q.poll();
if(dist[poll.node] < poll.weight)
continue;
for (Node next : list[poll.node]) {
if(dist[next.node] > dist[poll.node] + next.weight){
dist[next.node] = dist[poll.node] + next.weight;
q.add(new Node(next.node,dist[next.node]));
}
}
}
for(int i=1;i<=V;i++) {
if(dist[i] == MAX_DIST)
System.out.println("INF");
else
System.out.println(dist[i]);
}
}
static class Node implements Comparable<Node>{
int node;
int weight;
public Node(int node, int weight) {
this.node = node;
this.weight = weight;
}
@Override
public int compareTo(Node o) {
return this.weight-o.weight;
}
}
}
|
cs |
근데 왜지 ..? n^2 시간복잡도 방식이 시간이 덜 걸린 이유는 .. ? ㅋㅋ..
'알고리즘,PS > 백준' 카테고리의 다른 글
[BOJ] 백준 [1162] 도로포장 JAVA (0) | 2021.09.02 |
---|---|
[BOJ] 백준 [1916] 최소비용 구하기 JAVA (0) | 2021.09.02 |
[BOJ] 백준 [1194] 달이 차오른다, 가자. JAVA (0) | 2021.08.30 |
[BOJ] 백준 [14503] 로봇 청소기 JAVA (0) | 2021.08.27 |
[BOJ] 백준 [1966] 프린터 큐 JAVA (0) | 2021.08.26 |