본문 바로가기

ALGORITHM

백준 1939 중량제한 (Java)

1. 문제 링크

 

1939번: 중량제한

첫째 줄에 N, M(1 ≤ M ≤ 100,000)이 주어진다. 다음 M개의 줄에는 다리에 대한 정보를 나타내는 세 정수 A, B(1 ≤ A, B ≤ N), C(1 ≤ C ≤ 1,000,000,000)가 주어진다. 이는 A번 섬과 B번 섬 사이에 중량제한이

www.acmicpc.net

 

2. 문제 및 입출력예제

 

3. 문제 풀이

1. 최대 중량을 넘지 않는 최댓값을 찾아야 한다.

2. 두 섬을 연결시켜야 해서 BFS 탐색을 이용했고, 시간 초과를 생각해 이분 탐색을 함께 이용했다.

 

4. 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Queue;

public class Main {
	static class Point {
		int island;
		int weight;
		public Point(int island, int weight) {
			super();
			this.island = island;
			this.weight = weight;
		}
	}
	
	static int N, M, fact, ory, max, min;
	static boolean[] visit;
	static ArrayList<Point>[] list;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
        String[] split = br.readLine().split(" ");
        N = Integer.parseInt(split[0]);
        M = Integer.parseInt(split[1]);
        
        list = new ArrayList[N+1];
        for(int i=0;i<N+1;i++) {
        	list[i] = new ArrayList<>();
        }
        for(int i=0;i<M;i++) {
        	split = br.readLine().split(" ");
        	int a = Integer.parseInt(split[0]);
        	int b = Integer.parseInt(split[1]);
        	int c = Integer.parseInt(split[2]);
        	list[a].add(new Point(b, c));
        	list[b].add(new Point(a, c));
        	
        	max = Math.max(max, c);
        }

        split = br.readLine().split(" ");
        fact = Integer.parseInt(split[0]);
        ory = Integer.parseInt(split[1]);
        
        while(min <= max) {
        	boolean flag = false;
        	
        	int mid = (min + max) / 2;
        	
        	Queue<Integer> queue = new ArrayDeque<>();
        	visit = new boolean[N+1];
        	queue.offer(fact);
        	visit[fact] = true;
        	
        	while(!queue.isEmpty()) {
        		int now = queue.poll();
        		
        		if(now == ory) {
        			flag = true;
        			break;
        		}
        		
        		for(int i=0;i<list[now].size();i++) {
        			Point p = list[now].get(i);
        			if(p.weight >= mid 
        				&& !visit[p.island]) {
        				visit[p.island] = true;
        				queue.offer(p.island);
        			}
        		}
        	}
        	
        	if(flag) {
        		min = mid + 1;
        	}
        	else {
        		max = mid - 1;
        	}
        }
        System.out.println(max);
    }
}

 

'ALGORITHM' 카테고리의 다른 글

백준 15565 귀여운 라이언 (Java)  (0) 2023.09.19
백준 13335 트럭 (Java)  (0) 2023.09.17
백준 2056 작업 (Java)  (0) 2023.09.14
백준 2831 댄스 파티 (Java)  (0) 2023.09.12
백준 15684 사다리 조작 (Java)  (0) 2023.09.11