반응형
https://www.acmicpc.net/problem/18223
18223번: 민준이와 마산 그리고 건우
입력의 첫 번째 줄에 정점의 개수 V와 간선의 개수 E, 그리고 건우가 위치한 정점 P가 주어진다. (2 ≤ V ≤ 5,000, 1 ≤ E ≤ 10,000, 1 ≤ P ≤ V) 두 번째 줄부터 E개의 줄에 걸쳐 각 간선의 정보
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;
}
public int compareTo(Edge e){
return c - e.c;
}
}
public class Main {
static int v, e, p;
static ArrayList<Edge> adj[];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
v = sc.nextInt();
e = sc.nextInt();
p = sc.nextInt();
adj = new ArrayList[v+1];
for(int i=0; i<=v; i++){
adj[i] = new ArrayList<>();
}
for(int i=0; i<e; 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));
}
if(dikstra(1,v)==dikstra(1,p) + dikstra(p,v)){
System.out.println("SAVE HIM");
}
else System.out.println("GOOD BYE");
}
static int dikstra(int st, int en){
if(st==en) return 0;
PriorityQueue<Edge> Q = new PriorityQueue<>();
int dist[] = new int[v+1];
Arrays.fill(dist, Integer.MAX_VALUE);
Q.add(new Edge(st,0));
while(!Q.isEmpty()){
Edge cur = Q.poll();
for(Edge nx : adj[cur.x]){
if(dist[nx.x] > cur.c + nx.c){
dist[nx.x] = cur.c + nx.c;
Q.add(new Edge(nx.x, cur.c+nx.c));
}
}
}
return dist[en];
}
}
반응형
'Algorithm > problem' 카테고리의 다른 글
[LeetCode] best-position-for-a-service-centre - ternary search (0) | 2022.06.22 |
---|---|
[LeetCode] Split Array Largest Sum - Binary Search (0) | 2022.06.22 |
백준 20010번 : 악덕 영주 혜유 - Java 크루스칼, 다익스트라 (0) | 2022.06.11 |
백준 1719번: 택배 - 플로이드와샬 Java (0) | 2022.06.11 |
백준 5972번 : 택배 배송 Java 다익스트라 (0) | 2022.06.11 |