ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [백준/JAVA] 2217번: 로프
    Algorithm/Java 2024. 7. 16. 15:32

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

     

    - 정답 코드

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Arrays;
    
    public class Main {
        // 10 10 가능
        // 10 15 -> 하나당 감당 무게 25 / 2 = 12  ---> 불가
        // 15 15 불가 
        public static void main(String[] args) throws IOException{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int N = Integer.parseInt(br.readLine()); // 로프의 개수
            int[] ropes = new int[N]; // 각 로프가 버틸 수 있는 최대 중량 저장 배열
    
            for(int i = 0; i < N; i++) {
                ropes[i] = Integer.parseInt(br.readLine()); // [10, 15]
            }
    
            Arrays.sort(ropes); // 로프 오름차순 정렬 10 15 
    
            int maxWeight = 0;
    
            for(int i = 0; i < N; i++) {
                // (N - i)는 현재 로프와 그 이후의 로프들의 개수
                // 2 - 0 , 2 - 1 
                int currentWeight = ropes[i] * (N-i); 
                // 10 * 2 = 20 , 15 * 1 = 15
    
                if(currentWeight > maxWeight) {
                    maxWeight = currentWeight; 
                }  
            }
            System.out.println(maxWeight); // 20
        }
    }

    - 문제 풀이

    1. 로프 정렬

    최대 중량을 찾기 위해 로프들을 내림차순으로 정렬합니다. 이렇게 하면 가장 강한 로프부터 고려할 수 있습니다.

     

    2. 최대 중량 계산

    정렬된 로프들을 이용하여 가능한 최대 중량을 계산합니다.

    i번째 로프를 사용할 때, (i+1)개의 로프를 이용하여 들어올릴 수 있는 최대 중량은 ropes[i] * (i+1)입니다. 이를 모든 로프에 대해 계산하여 최대 중량을 찾습니다

     

     int maxWeight = 0;
    
            for(int i = 0; i < N; i++) {
                // (N - i)는 현재 로프와 그 이후의 로프들의 개수
                int currentWeight = ropes[i] * (N-i); 
    
                if(currentWeight > maxWeight) {
                    maxWeight = currentWeight; 
                }  
            }

     

    ex)N=3이고 로프들이 [10, 15, 20]일 경우

    1. i=0: currentWeight = 10 * 3 = 30 (10을 견디는 3개의 로프)
    2. i=1: currentWeight = 15 * 2 = 30 (15를 견디는 2개의 로프)
    3. i=2: currentWeight = 20 * 1 = 20 (20을 견디는 1개의 로프)

    이렇게 반복문을 통해 계산된 최대 중량은 30이 됩니다.

Designed by Tistory.