본문 바로가기
Problem Solving/Baekjoon

[백준] 1417 국회의원 선거 - Greedy / Java

by graycode 2023. 10. 20.

 문제 링크

 

1417번: 국회의원 선거

첫째 줄에 후보의 수 N이 주어진다. 둘째 줄부터 차례대로 기호 1번을 찍으려고 하는 사람의 수, 기호 2번을 찍으려고 하는 수, 이렇게 총 N개의 줄에 걸쳐 입력이 들어온다. N은 50보다 작거나 같

www.acmicpc.net

 

 풀이 코드

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Collections;
import java.util.PriorityQueue;

public class Main {

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

        int n = read(), a = read();

        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
        while (n-- > 1) pq.offer(read());

        int cnt = 0;
        while (!pq.isEmpty() && a <= pq.peek()) {
            pq.offer(pq.poll() - 1);
            a++;
            cnt++;
        }

        bw.write(String.valueOf(cnt));
        bw.flush();
    }

    private static int read() throws IOException {
        int c, n = System.in.read() & 15;
        while ((c = System.in.read()) > 32) n = (n << 3) + (n << 1) + (c & 15);

        return n;
    }

}

댓글