HelloMinchan
처음처럼
HelloMinchan
LinkedIn
전체 방문자
오늘
어제
  • 분류 전체보기 (306)
    • Backend (4)
      • NestJS (1)
      • Express (1)
      • Spring (2)
    • Infrastructure (1)
      • AWS (1)
    • Frontend (1)
      • Next.js (1)
    • Language & Runtime (4)
      • Java (2)
      • Node.js (2)
    • Computer Science (8)
      • Computer Networks (3)
      • Operating Systems (4)
      • OOP (1)
    • 독서 (4)
      • 데이터 중심 애플리케이션 설계 (3)
      • 객체지향의 사실과 오해 (1)
    • 회고 (4)
      • Project (2)
      • Career (2)
    • Deprecated (280)

채널

  • GitHub
  • LinkedIn

최근 글

태그

  • 백준Python
  • 백준
  • 백엔드
  • Baekjoon Online Judge
  • 데이터베이스
  • 백준Go
  • 알고스팟Python
  • 프로그래머스Python
  • front-end
  • 알고스팟
  • Database
  • 백준C++
  • 프로그래머스C++
  • 프로그래머스
  • programmers
  • 개발자
  • Algospot
  • 프로그래밍
  • 코딩
  • back-end

최근 댓글

인기 글

hELLO
HelloMinchan

처음처럼

[Baekjoon Online Judge] 백준 1655번 가운데를 말해요(C++, Python)
Deprecated

[Baekjoon Online Judge] 백준 1655번 가운데를 말해요(C++, Python)

2020. 4. 27. 18:34

© 2020 All Rights Reserved. 주식회사 스타트링크

[Baekjoon Online Judge] 백준 1655번 가운데를 말해요

(C++, Python)

(글쓴날 : 2020.04.27)

 


* Baekjoon Online Judge, 백준 1655번 문제 C++, Python 언어 풀이입니다.

* 소스 코드의 저작권은 글쓴이에게 있습니다.


 

 

백준 1655번 가운데를 말해요


1) 문제

문제 링크 : https://www.acmicpc.net/problem/1655

 

1655번: 가운데를 말해요

첫째 줄에는 수빈이가 외치는 정수의 개수 N이 주어진다. N은 1보다 크거나 같고, 100,000보다 작거나 같은 자연수이다. 그 다음 N줄에 걸쳐서 수빈이가 외치는 정수가 차례대로 주어진다. 정수는 -10,000보다 크거나 같고, 10,000보다 작거나 같다.

www.acmicpc.net


2) 풀이 과정

* 시간 복잡도 : O(n log n)

 

N개의 정수가 주어질 때마다 현재까지 주어진 정수 중에서 중간값을 구하는 문제입니다.

단, 정수의 개수가 짝수일 경우 가운데의 두 수 중 작은 수를 출력합니다.

 

저의 경우, 우선순위 큐를 적용하였으며, C++과 Python을 사용했습니다.

문제에서 주어지는 N이 최대 100000이므로 만약, 총 시간 복잡도가 O(n²)이 되는 로직을 구현 시 시간 초과가 발생하게 됩니다.

따라서, 중간값을 O(log n)에 찾기 위해 우선순위 큐를 적용했고,

내부를 각각 Min Heap과 Max Heap으로 구현한 우선순위 큐 두 개를 생성하여, 중간 값을 기준으로 작은 값들을 Max Heap 기반 우선순위 큐에, 큰 값들을 Min Heap 기반 우선순위 큐에 저장하고 동시에 중간 값을 계속 갱신하여 문제를 해결했습니다.


3) 코드

 

* C++ 코드

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
#include <queue>
#include <vector>
#include <functional>
#include <cstdlib>
 
using namespace std;
 
int main(void)
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
 
    int N = 0;
    cin >> N;
 
    int middleValue = 0;
    priority_queue<int> smallPQ;
    int smallPQCount = 0;
    priority_queue<int, vector<int>, greater<int>> bigPQ;
    int bigPQCount = 0;
 
    int tempValue = 0;
    int inputValue = 0;
 
    for (int i = 0; i < N; i++)
    {
        cin >> inputValue;
 
        if (!i)
        {
            middleValue = inputValue;
            cout << middleValue << "\n";
            continue;
        }
 
        if (inputValue >= middleValue)
        {
            smallPQ.push(middleValue);
            smallPQCount++;
 
            if (!abs(smallPQCount - bigPQCount))
            {
                bigPQ.push(inputValue);
                middleValue = bigPQ.top();
                bigPQ.pop();
                cout << middleValue << "\n";
            }
            else if (abs(smallPQCount - bigPQCount) == 2)
            {
                tempValue = smallPQ.top();
                smallPQ.pop();
                smallPQCount--;
                bigPQ.push(inputValue);
                bigPQCount += 1;
                bigPQ.push(tempValue);
                middleValue = bigPQ.top();
                bigPQ.pop();
                cout << middleValue << "\n";
            }
            else
            {
                cout << middleValue << "\n";
                bigPQ.push(inputValue);
                middleValue = bigPQ.top();
                bigPQ.pop();
            }
        }
        else
        {
            bigPQ.push(middleValue);
            bigPQCount++;
 
            if (!abs(smallPQCount - bigPQCount))
            {
                smallPQ.push(inputValue);
                middleValue = smallPQ.top();
                smallPQ.pop();
                cout << middleValue << "\n";
            }
            else if (abs(smallPQCount - bigPQCount) == 2)
            {
                tempValue = bigPQ.top();
                bigPQ.pop();
                bigPQCount--;
                smallPQ.push(inputValue);
                smallPQCount += 1;
                smallPQ.push(tempValue);
                middleValue = smallPQ.top();
                smallPQ.pop();
                cout << middleValue << "\n";
            }
            else
            {
                smallPQ.push(inputValue);
                middleValue = smallPQ.top();
                smallPQ.pop();
                cout << middleValue << "\n";
            }
        }
    }
 
    return 0;
}

* Python 코드

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import sys, heapq
input = sys.stdin.readline
 
N = int(input())
middleValue = 0
smallHQ = []
smallHQCount = 0
bigHQ = []
bigHQCount = 0
 
for i in range(N):
    inputValue = int(input())
 
    if not i:
        middleValue = inputValue
        print(middleValue)
        continue
    
    if inputValue >= middleValue:
        heapq.heappush(smallHQ, (-middleValue, middleValue))
        smallHQCount += 1
 
        if not abs(smallHQCount - bigHQCount):
            heapq.heappush(bigHQ, (inputValue, -inputValue))
            middleValue = -heapq.heappop(bigHQ)[1]
            print(middleValue)
        elif abs(smallHQCount - bigHQCount) == 2:
            tempValue = heapq.heappop(smallHQ)[1]
            smallHQCount -= 1
            heapq.heappush(bigHQ, (inputValue, -inputValue))
            bigHQCount += 1
            heapq.heappush(bigHQ, (tempValue, -tempValue))
            middleValue = -heapq.heappop(bigHQ)[1]
            print(middleValue)
        else:
            print(middleValue)
            heapq.heappush(bigHQ, (inputValue, -inputValue))
            middleValue = -heapq.heappop(bigHQ)[1]
    else:
        heapq.heappush(bigHQ, (middleValue, -middleValue))
        bigHQCount += 1
 
        if not abs(smallHQCount - bigHQCount):
            heapq.heappush(smallHQ, (-inputValue, inputValue))
            middleValue = heapq.heappop(smallHQ)[1]
            print(middleValue)
        elif abs(smallHQCount - bigHQCount) == 2:
            tempValue = -heapq.heappop(bigHQ)[1]
            bigHQCount -= 1
            heapq.heappush(smallHQ, (-inputValue, inputValue))
            smallHQCount += 1
            heapq.heappush(smallHQ, (-tempValue, tempValue))
            middleValue = heapq.heappop(smallHQ)[1]
            print(middleValue)
        else:
            heapq.heappush(smallHQ, (-inputValue, inputValue))
            middleValue = heapq.heappop(smallHQ)[1]
            print(middleValue)

 

저작자표시 비영리 변경금지 (새창열림)

'Deprecated' 카테고리의 다른 글

[ALGOSPOT] 알고스팟 MATCHORDER 출전 순서 정하기(C++, Python)  (0) 2020.04.29
[ALGOSPOT] 알고스팟 LUNCHBOX Microwaving Lunch Boxes(C++, Python)  (0) 2020.04.29
[Baekjoon Online Judge] 백준 1715번 카드 정렬하기(C++, Python)  (0) 2020.04.27
[Baekjoon Online Judge] 백준 11286번 절댓값 힙(C++, Python)  (0) 2020.04.26
[Python] heapq 사용법  (0) 2020.04.26
    'Deprecated' 카테고리의 다른 글
    • [ALGOSPOT] 알고스팟 MATCHORDER 출전 순서 정하기(C++, Python)
    • [ALGOSPOT] 알고스팟 LUNCHBOX Microwaving Lunch Boxes(C++, Python)
    • [Baekjoon Online Judge] 백준 1715번 카드 정렬하기(C++, Python)
    • [Baekjoon Online Judge] 백준 11286번 절댓값 힙(C++, Python)
    HelloMinchan
    HelloMinchan
    Though you should not fear failure, You should do your very best to avoid it.

    티스토리툴바