상세 컨텐츠

본문 제목

[C++] 11286 : 절댓값 힙

프로그래밍/백준

by whave 2022. 4. 14. 14:42

본문

#include<iostream>
#include<cstdlib>
#include<queue>
using namespace std; 

int main(void){
	int n,i,input;
	priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
	cin >> n;
	for(i=0;i<n;i++){
		cin >> input;
		if(input!=0){
			pq.push(make_pair(abs(input),input));
		}
		else{ //input이 0이면 절대값 최소 중 최소 값 출력
			if(!pq.empty()){
				cout << pq.top().second << endl;
				pq.pop();
			}
			else{
				cout << "0\n";
			}
		}
	}
	return 0;
}

 

 

1. 배열에서 최소값을 찾아야 하므로 최소힙 구조를 사용해 빠른 탐색
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
참고: https://developingbear.tistory.com/58

2. 절대값 함수 abs 
헤더파일  - int형 반환일 떄 <cstdlib>
- 실수형 반환일 때 <cmath>
참고: https://blockdmask.tistory.com/335

3.queue와 pair을 함께 사용할 때 pair 값에 접근 하는 방법
pq.top().first 
pq.top().second

'프로그래밍 > 백준' 카테고리의 다른 글

11723 : 집합  (0) 2022.03.14
[C언어/그리디] 1931 : 회의실 배정  (0) 2022.03.03
[C언어/그리디]1026 : 보물  (0) 2022.03.02
[C++/다익스트라] 1753 : 최단경로  (0) 2022.02.16
[C언어/DP] 9465 : 스티커  (0) 2022.02.12

관련글 더보기