Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 백준 토마토
- 백준 1049번 기타줄
- 백준 14246번
- c++ 조합
- 백준 10709
- 백준 14246번 K보다 큰 구간
- 성북구 학원
- 고정 소수점
- 월곡동 학원추천
- 백준 패션왕 신해빈
- DFS
- C++ 9996
- OS
- 백준 1049번
- 백준 9375번 패션왕 신해빈
- C# 병합정렬
- 백준 K보다 큰 구간
- 월곡역 학원
- 백준 한국이 그리울 땐 서버에 접속하지
- 월곡중 학원
- 백준 2309번 일곱 난쟁이
- 백준 dfs
- 관리형 학원
- C++ 문자열
- 운영체제
- 상월곡동 학원
- 서울사대부고 학원
- 상월곡역 학원
- c++ split
- 월곡중학교 학원추천
Archives
- Today
- Total
키베이루's diary
[C++] 백준 1655번 가운데를 말해요 본문
1) 문제설명
https://www.acmicpc.net/problem/1655
1655번: 가운데를 말해요
첫째 줄에는 백준이가 외치는 정수의 개수 N이 주어진다. N은 1보다 크거나 같고, 100,000보다 작거나 같은 자연수이다. 그 다음 N줄에 걸쳐서 백준이가 외치는 정수가 차례대로 주어진다. 정수는 -1
www.acmicpc.net
2) 아이디어
우선순위 큐의 최대 힙과 최소 힙을 둘 다 사용하여 가운데 값을 구해야 한다.
1. 홀수번째 수 일 경우 최대 힙에 값을 넣고
2. 짝수번째 수 일 경우 최소 힙에 값을 넣는다.
3. 최대 힙의 최댓값이 최소 힙의 최솟값보다 작을 경우 두 원소를 바꿔준다.
3) 코드
실패한 코드 : 시간 초과
#include<iostream>
#include<queue>
#include<deque>
#include<string.h>
#include<math.h>
#include<cmath>
#include<stack>
#include<algorithm>
using namespace std;
int cnt = 0;
int flag = 1;
int main() {
int n;
int arr[200001];
priority_queue <int,vector<int>,greater<int>> pq;
priority_queue <int, vector<int>, greater<int>> pq2;
queue<int> q;
cin >> n;
for (int i = 1; i <= n; i++) {
int a;
cin >> a;
pq.push(a);
if (i >= 3) {
int temp = pq.size();
while (cnt < temp/2) {
if (temp % 2 == 0 && flag == 1) {
cnt = 1;
flag = 0;
}
cnt++;
arr[cnt] = pq.top();
pq.pop();
}
cout << pq.top() << endl;
while (cnt > 0) { // 1
pq.push(arr[cnt]);
cnt--;
}
}
cnt = 0;
if (i < 3) {
cout << pq.top() << endl;
}
}
}
성공한 코드
#include<iostream>
#include<queue>
#include<deque>
#include<string.h>
#include<math.h>
#include<cmath>
#include<stack>
#include<algorithm>
using namespace std;
int cnt = 1;
int flag = 1;
int main() {
int n;
int arr[200001];
priority_queue <int,vector<int>,greater<int>> minheap; // 오름차순 2
priority_queue <int, vector<int>, less <int >> maxheap; // 내림차순 3 , 1
cin >> n;
while (n--) {
int a;
scanf("%d", &a);
cnt++;
if (cnt % 2 == 1) {
minheap.push(a);
}
else {
maxheap.push(a);
}
if (cnt >= 3) {
if (minheap.top() <= maxheap.top()) {
int temp1 = minheap.top();
int temp2 = maxheap.top();
minheap.pop();
maxheap.pop();
minheap.push(temp2);
maxheap.push(temp1);
}
}
printf("%d\n", maxheap.top());
}
}
'알고리즘 > 기타' 카테고리의 다른 글
[C++] 백준 10815번 숫자 카드 (0) | 2022.07.05 |
---|---|
[C++] 백준 16953번 A -> B (0) | 2022.06.21 |
[C++] 백준 11286번 절댓값 힙 (0) | 2022.06.09 |
[C++] Vector (0) | 2022.06.03 |
[C++] 백준 18870번 좌표압축 (0) | 2022.05.26 |
Comments