[백준] 1939번 중량제한 Java

JeongYong·2022년 12월 28일
0

Algorithm

목록 보기
89/263

문제 링크

https://www.acmicpc.net/problem/1939

문제

N(2 ≤ N ≤ 10,000)개의 섬으로 이루어진 나라가 있다. 이들 중 몇 개의 섬 사이에는 다리가 설치되어 있어서 차들이 다닐 수 있다.

영식 중공업에서는 두 개의 섬에 공장을 세워 두고 물품을 생산하는 일을 하고 있다. 물품을 생산하다 보면 공장에서 다른 공장으로 생산 중이던 물품을 수송해야 할 일이 생기곤 한다. 그런데 각각의 다리마다 중량제한이 있기 때문에 무턱대고 물품을 옮길 순 없다. 만약 중량제한을 초과하는 양의 물품이 다리를 지나게 되면 다리가 무너지게 된다.

한 번의 이동에서 옮길 수 있는 물품들의 중량의 최댓값을 구하는 프로그램을 작성하시오.

입력

첫째 줄에 N, M(1 ≤ M ≤ 100,000)이 주어진다. 다음 M개의 줄에는 다리에 대한 정보를 나타내는 세 정수 A, B(1 ≤ A, B ≤ N), C(1 ≤ C ≤ 1,000,000,000)가 주어진다. 이는 A번 섬과 B번 섬 사이에 중량제한이 C인 다리가 존재한다는 의미이다. 서로 같은 두 섬 사이에 여러 개의 다리가 있을 수도 있으며, 모든 다리는 양방향이다. 마지막 줄에는 공장이 위치해 있는 섬의 번호를 나타내는 서로 다른 두 정수가 주어진다. 공장이 있는 두 섬을 연결하는 경로는 항상 존재하는 데이터만 입력으로 주어진다.

출력

첫째 줄에 답을 출력한다.

알고리즘: BFS, 이분 탐색

풀이

최소 중량과 최대 중량을 설정하고, 이분 탐색으로 도착지까지 수송할 수 있는 최대 중량을 구한다.

mid_weight값으로 너비 우선 탐색을 진행했을 때, 탐색에 성공한다면 min_weight값을 업데이트해 주고, 탐색에 실패했다면 max_weight값을 업데이트해 준다.

위 방식을 min_weight값과 max_weight값이 같아질 때까지 반복해준다.

시간 복잡도를 계산해보면 인접 리스트이기 때문에 O(V+E)이고 이분 탐색 O(log2C)로 TLE없이 통과할 수 있다. (약110000 * 30)

소스 코드

import java.io.*;
import java.util.*;

public class Main {
    static int N,M;
    static ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
    static boolean visited[];
    static HashMap<Integer, HashMap<Integer, Long>> weight_map = new HashMap<>();
    static int start,end;
    public static void main(String args[]) throws IOException {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      StringTokenizer st = new StringTokenizer(br.readLine());
      N = Integer.parseInt(st.nextToken());
      M = Integer.parseInt(st.nextToken());
      for(int i=0; i<=N; i++) {
          graph.add(new ArrayList<>());
          weight_map.put(i, new HashMap<>());
      }
      for(int i=0; i<M; i++) {
          StringTokenizer n_st = new StringTokenizer(br.readLine());
          int A = Integer.parseInt(n_st.nextToken());
          int B = Integer.parseInt(n_st.nextToken());
          long C = Long.parseLong(n_st.nextToken());
          graph.get(A).add(B);
          graph.get(B).add(A);
          if(weight_map.get(A).get(B) == null) {
              weight_map.get(A).put(B, C);
              weight_map.get(B).put(A, C);
          } else {
              if(weight_map.get(A).get(B) < C) {
                  weight_map.get(A).put(B, C);
                  weight_map.get(B).put(A, C);
              }
          }
      }
      StringTokenizer n_st = new StringTokenizer(br.readLine());
      start = Integer.parseInt(n_st.nextToken());
      end = Integer.parseInt(n_st.nextToken());
      //최소 중량, 최대 중량 구하기
      long min_weight = 1;
      long max_weight = -1;
      for(int i=0; i<graph.get(start).size(); i++) {
          int b = graph.get(start).get(i);
          if(max_weight < weight_map.get(start).get(b)) max_weight = weight_map.get(start).get(b);
      }
      //이분 탐색
      while(min_weight != max_weight) {
          long mid_weight;
          if((min_weight + max_weight)%2 == 0) mid_weight = (min_weight + max_weight)/2;
          else mid_weight = (min_weight + max_weight)/2 + 1;
          //최소 중량, 최대 중량 업데이트
          visited = new boolean[N+1];
          if(BFS(mid_weight)) {
              min_weight = mid_weight;
          } else {
              max_weight = mid_weight - 1;
          }
      }
      System.out.println(min_weight);
    }
    
    static boolean BFS(long w) {
        Queue<Integer> que = new LinkedList<>();
        que.add(start);
        visited[start] = true;
        while(que.size() != 0) {
            int land = que.poll();
            if(land == end) return true; //탐색 성공
            for(int i=0; i<graph.get(land).size(); i++) {
                int d_land = graph.get(land).get(i);
                if(!visited[d_land] && (w <=weight_map.get(land).get(d_land))) {
                    que.add(d_land);
                    visited[d_land] = true;
                }
            }
        }
        return false; //실패
    }
}

0개의 댓글