728x90
문제
0이 아닌 숫자가 들어오면 대기열에 넣는다
0이 들어왔을 때, 대기열에 숫자가 있으면 하나씩 빼서 출력
0이 들어왔을 때, 대기열에 숫자가 없으면 0을 출력
단, 대기열에 숫자는 절대값이 작은 순서로 뺌
단, 대기열의 숫자 중 절대값이 같은 수가 있으면, 더 작은 수를 뺌
문제 링크 : https://www.acmicpc.net/problem/11286
원리
PriorityQueue 사용
PriorityQueue에 조건 만들어주는게 핵심
풀이방법
두 수 a, b를 두고 비교
a와 b의 각각의 절대값이 같을 경우, a와 b 두 수의 부호가 다르면 음수를 앞으로 리턴(가령 2와 -2)
a와 b중 절대값이 작은 수를 앞으로 리턴
나의 코드
public class no11286 {
private static PriorityQueue<Integer> queue;
private static BufferedWriter bw;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
int T = Integer.parseInt(br.readLine());
queue = new PriorityQueue<>((a,b) -> {
if(Math.abs(a) == Math.abs(b)) return a > b ? 1 : -1;
return Math.abs(a) - Math.abs(b);
}); // 핵심로직 : 우선순위 큐. 절대값이 같으면 더 작은놈. 그 외엔 절대값이 더 작은 놈을 우선 뺌
for(int i=0; i<T ; i++) {
Integer num = Integer.parseInt(br.readLine());
calculate(num);
}
bw.close();
}
private static void calculate (Integer num) throws IOException {
if(num.equals(0)) {
if(queue.isEmpty()) bw.write("0\n");
else bw.write(""+queue.poll()+"\n");
}
else queue.add(num);
}
}
레퍼런스 코드
참고 링크 : https://dragon-h.tistory.com/5
728x90
'알고리즘 저장소 (일반방식과 나만의 풀이) > JAVA' 카테고리의 다른 글
| [백준] no11724: 연결 요소의 개수 (0) | 2023.02.14 |
|---|---|
| [백준] no11403: 경로 찾기 (0) | 2023.02.13 |
| [백준] no14500: 테트로미노 (0) | 2023.02.10 |
| [백준] no18870: 좌표압축 (0) | 2023.02.10 |
| [백준] no1992: 쿼드트리 (0) | 2023.02.09 |