https://www.acmicpc.net/problem/2470
2470번: 두 용액
첫째 줄에는 전체 용액의 수 N이 입력된다. N은 2 이상 100,000 이하이다. 둘째 줄에는 용액의 특성값을 나타내는 N개의 정수가 빈칸을 사이에 두고 주어진다. 이 수들은 모두 -1,000,000,000 이상 1,000,00
www.acmicpc.net
이 문제를 해결하기 위해서는 우선순위 큐를 이용하여 오름차순 큐와 내림차순의 큐를 각각 만들어 준 후, 위에서 하나씩 뽑아 그 수의 차의 절대값을 비교하여 문제를 풀었다.
그 후, 계속 하나씩 뽑다가 뽑은 개수가 N개에 도달했을 때 루프를 멈춘 후 해당 숫자가 답이 된다.
package PriorityQueue;
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 N2470 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
PriorityQueue<Integer> lowq = new PriorityQueue<>(Collections.reverseOrder());
PriorityQueue<Integer> highq = new PriorityQueue<>();
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
int num = Integer.parseInt(st.nextToken());
lowq.add(num);
highq.add(num);
}
int lowcount = 0;
int highcount = 0;
int diff = 2000000001;
int lownum = 0;
int highnum = 0;
while(true){
if(lowcount + highcount == N-1) break;
if(lowq.peek()+highq.peek()<0){
if(Math.abs(lowq.peek()+highq.peek()) < diff){
diff = Math.abs(lowq.peek()+highq.peek());
lownum = lowq.peek();
highnum = highq.peek();
}
highq.poll();
highcount++;
}
else {
if(Math.abs(lowq.peek()+highq.peek()) < diff){
diff = Math.abs(lowq.peek()+highq.peek());
lownum = lowq.peek();
highnum = highq.peek();
}
lowq.poll();
lowcount++;
}
}
System.out.print(highnum + " ");
System.out.print(lownum);
}
}'백준문제 > 자료구조' 카테고리의 다른 글
| 1068-트리 (0) | 2023.03.06 |
|---|---|
| 1966-프린터 큐 (1) | 2023.02.04 |