Coding Test

백준 로프(2217)

댕발바닥 2024. 3. 1. 18:11

 

그리디 문제를 한개 더풀어봤다 생각보다 이 알고리즘이 재미가 있다.

 

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

 

2217번: 로프

N(1 ≤ N ≤ 100,000)개의 로프가 있다. 이 로프를 이용하여 이런 저런 물체를 들어올릴 수 있다. 각각의 로프는 그 굵기나 길이가 다르기 때문에 들 수 있는 물체의 중량이 서로 다를 수도 있다. 하

www.acmicpc.net

 

로프의 개수가 늘어날수록 (로프 리스트 중 가장 낮은값 * 로프 개수가) 최대 무게가 된다 이러한 방식으로 정렬되어있는 로프를 순서대로 최적해를 찾아가면 된다.

 

package greedy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class Q2217 {

    public static void main(String[] args) throws IOException {
        greedy();
    }

    public static void greedy() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int answer = 0;
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(((o1, o2) -> o2 - o1));
        for (int i=0; i < n; i++) {
            priorityQueue.add(Integer.parseInt(br.readLine()));
        }

        int size = 1;
        while (!priorityQueue.isEmpty()) {
            int weight = priorityQueue.poll();
            if (answer < weight * size) answer = weight * size;
            size++;
        }

        System.out.println(answer);
    }
}

 

결과