https://www.acmicpc.net/problem/1916
1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그
www.acmicpc.net
문제
풀이
풀이 방식은 이전 포스팅과 동일하다.
https://katastrophe.tistory.com/19
[BOJ] 백준 [1753] 최단경로 JAVA
https://www.acmicpc.net/problem/1753 1753번: 최단경로 첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1≤V≤20,000, 1≤E≤300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째..
katastrophe.tistory.com
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
|
import java.util.*;
import java.io.*;
public class Main{
static int MAX_DIST = Integer.MAX_VALUE;
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));
V = Integer.parseInt(br.readLine()); E = 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++){
String[] input = br.readLine().split(" ");
list[Integer.parseInt(input[0])].add(new Node(Integer.parseInt(input[1]),Integer.parseInt(input[2])));
}
String[] input = br.readLine().split(" ");
int start = Integer.parseInt(input[0]); int end = Integer.parseInt(input[1]);
System.out.println(findShortPath(start,end));
}
static int findShortPath(int start,int end) {
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]));
}
}
}
return dist[end];
}
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 |
'알고리즘,PS > 백준' 카테고리의 다른 글
[BOJ] 백준 [1920] 수찾기 JAVA (0) | 2021.09.06 |
---|---|
[BOJ] 백준 [1162] 도로포장 JAVA (0) | 2021.09.02 |
[BOJ] 백준 [1753] 최단경로 JAVA (0) | 2021.09.01 |
[BOJ] 백준 [1194] 달이 차오른다, 가자. JAVA (0) | 2021.08.30 |
[BOJ] 백준 [14503] 로봇 청소기 JAVA (0) | 2021.08.27 |