반응형
https://www.acmicpc.net/problem/5972
5972번: 택배 배송
농부 현서는 농부 찬홍이에게 택배를 배달해줘야 합니다. 그리고 지금, 갈 준비를 하고 있습니다. 평화롭게 가려면 가는 길에 만나는 모든 소들에게 맛있는 여물을 줘야 합니다. 물론 현서는
www.acmicpc.net
import java.util.*;
class Edge implements Comparable<Edge>{
int x, c;
Edge(int x, int c){
this.x = x;
this.c = c;
}
@Override
public int compareTo(Edge e){
return c - e.c;
}
}
public class Main {
static int n,m;
static ArrayList<Edge> adj[];
static int dist[];
static PriorityQueue<Edge> Q = new PriorityQueue<>();
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
adj = new ArrayList[n+1];
dist = new int[n+1];
Arrays.fill(dist,Integer.MAX_VALUE);
for(int i=0; i<=n; i++){
adj[i] = new ArrayList<Edge>();
}
for(int i=0; i<m; i++){
int a, b, c;
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
adj[a].add(new Edge(b,c));
adj[b].add(new Edge(a,c));
}
dist[1] = 0;
Q.add(new Edge(1,0));
while(!Q.isEmpty()){
Edge cur = Q.poll();
if(cur.c > dist[cur.x]) continue;
dist[cur.x] = cur.c;
for(int i=0; i<adj[cur.x].size();i++){
Edge nx = adj[cur.x].get(i);
if(dist[nx.x] > nx.c + cur.c){
Q.add(new Edge(nx.x, nx.c + cur.c));
}
}
}
System.out.println(dist[n]);
}
}
반응형
'Algorithm > problem' 카테고리의 다른 글
백준 20010번 : 악덕 영주 혜유 - Java 크루스칼, 다익스트라 (0) | 2022.06.11 |
---|---|
백준 1719번: 택배 - 플로이드와샬 Java (0) | 2022.06.11 |
백준 1368번 : 물대기 - Java (0) | 2022.06.07 |
백준 1946번 : 신입사원 - Java fastio, Arraylist , Collections.sort (0) | 2022.05.24 |
백준 14950번: 정복자 prim 알고리즘 - Java (0) | 2022.05.22 |