[JAVA-자바] 1238번: 파티

2025. 5. 19. 16:24·알고리즘/백준

 

소스코드:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class Main {
    static BufferedReader br;
    static BufferedWriter bw;

    static int N, M, X;
    static List<List<Node>> graph;
    static List<List<Node>> graph_reverse;

    public static class Node {
        int to;
        int cost;

        Node(int t, int c) {
            this.to = t;
            this.cost = c;
        }
    }


    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        bw = new BufferedWriter(new OutputStreamWriter(System.out));

        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        X = Integer.parseInt(st.nextToken());

        graph = new ArrayList<>();
        graph_reverse = new ArrayList<>();

        for (int i = 0; i <= N; i++) {
            graph.add(new ArrayList<>());
            graph_reverse.add(new ArrayList<>());
        }

        for (int i = 0; i < M; i++) {
            st = new StringTokenizer(br.readLine());
            int start = Integer.parseInt(st.nextToken());
            int to = Integer.parseInt(st.nextToken());
            int cost = Integer.parseInt(st.nextToken());

            graph.get(start).add(new Node(to, cost));
            graph_reverse.get(to).add(new Node(start, cost));
        }
        br.close();

        int[] gogo = dijkstra(X, graph_reverse);
        int[] back = dijkstra(X, graph);

        int result = 0;
        for (int i = 1; i <= N; i++) {
            int calc = gogo[i] + back[i];
            result = Math.max(result, calc);
        }

        bw.write(result + "\n");
        bw.close();
    }

    public static int[] dijkstra(int start, List<List<Node>> g) {
        int[] distance = new int[N + 1];
        Arrays.fill(distance, Integer.MAX_VALUE);
        distance[start] = 0;

        PriorityQueue<int[]> pq = new PriorityQueue<>(((o1, o2) -> o1[1] - o2[1]));
        pq.add(new int[]{start, distance[start]});

        while (!pq.isEmpty()) {
            int[] cur = pq.poll();
            int cur_node = cur[0];
            int cur_distance = cur[1];

            if (cur_distance > distance[cur_node]) {
                continue;
            }

            for (Node near : g.get(cur_node)) {
                int next = near.to;
                int cost = near.cost;

                if (distance[next] > distance[cur_node] + cost) {
                    distance[next] = distance[cur_node] + cost;
                    pq.add(new int[]{next, distance[next]});
                }
            }
        }

        return distance;
    }
}

 

글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.

여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.

'알고리즘 > 백준' 카테고리의 다른 글

[JAVA-자바] 2206번: 벽 부수고 이동하기  (0) 2025.05.22
[JAVA-자바] 1865번: 웜홀  (0) 2025.05.21
[JAVA-자바] 17144번: 미세먼지 안녕!  (0) 2025.05.18
[JAVA-자바] 14938번: 서강그라운드  (0) 2025.05.16
[JAVA-자바] 14502번: 연구소  (0) 2025.05.15
'알고리즘/백준' 카테고리의 다른 글
  • [JAVA-자바] 2206번: 벽 부수고 이동하기
  • [JAVA-자바] 1865번: 웜홀
  • [JAVA-자바] 17144번: 미세먼지 안녕!
  • [JAVA-자바] 14938번: 서강그라운드
raven
raven
Github : https://github.com/RabeMaster | Email : ra___be@naver.com
  • raven
    배움을 원하는 사람
    raven
  • 전체
    오늘
    어제
  • 공지사항

    • 안녕하세요
    • 분류 전체보기 (169)
      • 네이버 부스트캠프 10기 (7)
        • 멤버십 (5)
        • 챌린지 (1)
        • 베이직 (1)
      • 공부 (2)
        • JAVA (1)
        • CS (0)
        • 정보처리기사 (1)
      • 알고리즘 (159)
        • 백준 (159)
      • 개발 (1)
        • 백준 확장 프로그램 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 인기 글

  • 태그

    너비 우선 탐색
    그래프 이론
    java
    코딩테스트
    다이나믹 프로그래밍
    알고리즘
    정렬
    회고
    코테
    개발
    그래프 탐색
    IT
    부스트캠프
    네이버부스트캠프
    백트래킹
    부트캠프
    그리디 알고리즘
    브루트포스 알고리즘
    자료 구조
    자바
    백준
    스택
    네부캠
    네이버
    멤버십
    구현
    수학
    문자열
    최단 경로
    코딩
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
raven
[JAVA-자바] 1238번: 파티
상단으로

티스토리툴바