728x90
반응형
1. 최소 힙(백준 1927번)
1927번: 최소 힙
첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0
www.acmicpc.net
▷ 풀이 코드
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collections; import java.util.PriorityQueue; public class MinHip { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int num = Integer.parseInt(br.readLine()); PriorityQueue<Integer> minQueue = new PriorityQueue<Integer>(); for(int i=0; i<num; i++) { int input = Integer.parseInt(br.readLine()); if(input == 0) { if(minQueue.size() <= 0) sb.append("0").append("\n"); else { sb.append(minQueue.poll()).append("\n"); } }else {minQueue.add(input);} } System.out.println(sb); } }
2. 최대 힙(백준 11279번 문제)
11279번: 최대 힙
첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0
www.acmicpc.net
▷ 풀이 코드
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collections; import java.util.PriorityQueue; public class Main { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int num = Integer.parseInt(br.readLine()); PriorityQueue<Integer> maxQueue = new PriorityQueue<Integer>(Collections.reverseOrder()); for(int i=0; i<num; i++) { int input = Integer.parseInt(br.readLine()); if(input == 0) { if(maxQueue.size() <= 0) sb.append("0").append("\n"); else { sb.append(maxQueue.poll()).append("\n"); } }else {maxQueue.add(input);} } System.out.println(sb); } }
이번에는 알고리즘 스터디를 통해 배운 큐를 통해 백준 문제 풀이를 해보았습니다!!
큐는 FIFO 구조이지만 우선 순위 Queue를 이용하면 해당 값이 출력되고 난 후 최솟값이 우선순위로 출력되도록 바뀌네요!
또한, Collections.reverseOrder를 사용하면 역순으로 최댓값이 우선순위로 출력되네요!!
Queue를 이용하니 Array, List, Map을 이용한 것보다 훨씬 더 빠르게 수행되는 것을 확인할 수 있어요
내장되어 있는 함수들을 잘 이용하는 것이 중요하다는 것을 알 수 있네요ㅎ
많은 분들의 피드백은 언제나 환영합니다! 많은 댓글 부탁드려요~~

728x90
반응형
'문제풀기 > 백준 문제풀이' 카테고리의 다른 글
[알고리즘] 큐 문제 풀이(백준 10845번, 1158번, 1966번) (2) | 2023.08.10 |
---|---|
[알고리즘] 우선순위 큐 문제 풀이 2 (백준 11286번) (0) | 2023.08.10 |
[알고리즘] 스택 문제 풀이(백준 9012번, 10773번, 10828번) (0) | 2023.08.03 |
[알고리즘] 해시 문제 풀이(백준 10816번, 1764번) (0) | 2023.07.27 |
[알고리즘] 브루트-포스법 문제 풀이(백준 2798번, 2231번) (4) | 2023.06.21 |