회원가입
로그인
Toggle navigation
문제
문제
전체 문제
문제 출처
단계별로 풀어보기
알고리즘 분류
추가된 문제
문제 순위
문제
푼 사람이 한 명인 문제
아무도 못 푼 문제
최근 제출된 문제
최근 풀린 문제
랜덤
출처
ICPC
Olympiad
한국정보올림피아드
한국정보올림피아드시․도지역본선
전국 대학생 프로그래밍 대회 동아리 연합
대학교 대회
카카오 코드 페스티벌
Coder's High
ICPC
Regionals
World Finals
Korea Regional
Africa and the Middle East Regionals
Europe Regionals
Latin America Regionals
North America Regionals
South Pacific Regionals
문제집
대회
채점 현황
게시판
그룹
더 보기
재채점 기록
블로그
도움말
전체
공지
자유
질문
오타/오역/요청
게시판 공지
홍보
업데이트
solved.ac
글쓰기
질문 도움말
자주묻는 질문
왜 틀렸습니다...?
1504번 - 특정한 최단 경로
doco827
2년 전
0
왜 틀렸습니다 가 뜰까요?
import java.io.*; import java.util.*; public class Main { static List<ArrayList<Node>> list; static int n, ans, e, U, V; static int[] load; public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); e = Integer.parseInt(st.nextToken()); int INF = 987654321; // 큰 숫자 list = new ArrayList<>(); for (int i = 0; i <= n; i++) list.add(new ArrayList<>()); // 초기화 for (int i = 1; i <= e; i++){ st= new StringTokenizer(br.readLine()); int s = Integer.parseInt(st.nextToken()); int e = Integer.parseInt(st.nextToken()); int cost = Integer.parseInt(st.nextToken()); list.get(s).add(new Node(e, cost)); // 양방향이기 때문에 양쪽 모두 저장 list.get(e).add(new Node(s, cost)); } st = new StringTokenizer(br.readLine()); U = Integer.parseInt(st.nextToken()); V = Integer.parseInt(st.nextToken()); load = new int[n + 1]; boolean go1, go2; go1 = go2 = true; Arrays.fill(load, INF); dijkstra(1); int u = load[U]; int v = load[V]; if (u == INF) go1 = false; if (v == INF) go2 = false; Arrays.fill(load, INF); dijkstra(U); if (go1) u += load[V]; if (go2) v += load[V]; Arrays.fill(load, INF); dijkstra(V); if (go1) u+= load[n]; Arrays.fill(load, INF); dijkstra(U); if (go2) v+= load[n]; if (!go1 && !go2) ans = -1; else { ans = Math.min(u, v); } if (ans == INF) ans = -1; System.out.println(ans); } static void dijkstra(int s){ PriorityQueue<Node> q = new PriorityQueue<>(); q.offer(new Node(s, 0)); load[s] = 0; // 초기화 while (!q.isEmpty()){ Node now = q.poll(); for (Node i : list.get(now.e)) { if (load[i.e] > now.cost + i.cost){ load[i.e] = now.cost + i.cost; q.offer(new Node(i.e,load[i.e])); } } } } static class Node implements Comparable<Node>{ int e, cost; public Node(int e, int cost) { this.e = e; this.cost = cost; } @Override public int compareTo(Node o) { return cost - o.cost; } } }
댓글을 작성하려면
로그인
해야 합니다.
doco827 2년 전
왜 틀렸습니다 가 뜰까요?