<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>중앙값 Archives - 어제와 내일의 나 그 사이의 이야기</title>
	<atom:link href="https://lycos7560.com/tag/%EC%A4%91%EC%95%99%EA%B0%92/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>생각의 흐름을 타고 다니며 만드는 블로그</description>
	<lastBuildDate>Mon, 13 Oct 2025 04:35:51 +0000</lastBuildDate>
	<language>ko-KR</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://lycos7560.com/wp-content/uploads/2022/11/cropped-cropped-cropped-log-1-150x150-1-80x80.png</url>
	<title>중앙값 Archives - 어제와 내일의 나 그 사이의 이야기</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>백준 1655번 (가운데를 말해요, C++)</title>
		<link>https://lycos7560.com/cpp/%eb%b0%b1%ec%a4%80-1655%eb%b2%88-%ea%b0%80%ec%9a%b4%eb%8d%b0%eb%a5%bc-%eb%a7%90%ed%95%b4%ec%9a%94-c/40309/</link>
					<comments>https://lycos7560.com/cpp/%eb%b0%b1%ec%a4%80-1655%eb%b2%88-%ea%b0%80%ec%9a%b4%eb%8d%b0%eb%a5%bc-%eb%a7%90%ed%95%b4%ec%9a%94-c/40309/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Mon, 13 Oct 2025 02:09:45 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[1655]]></category>
		<category><![CDATA[1655번]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[C++ 구현]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[O(log n)]]></category>
		<category><![CDATA[push-pop 연산]]></category>
		<category><![CDATA[study]]></category>
		<category><![CDATA[Two Heaps]]></category>
		<category><![CDATA[가운데를 말해요]]></category>
		<category><![CDATA[개발 능력]]></category>
		<category><![CDATA[게임 구현]]></category>
		<category><![CDATA[경계 조건]]></category>
		<category><![CDATA[계산적 사고]]></category>
		<category><![CDATA[고급 기법]]></category>
		<category><![CDATA[공간 복잡도]]></category>
		<category><![CDATA[공간 효율성]]></category>
		<category><![CDATA[공부]]></category>
		<category><![CDATA[교육적 예제]]></category>
		<category><![CDATA[구현 기술]]></category>
		<category><![CDATA[균형 유지]]></category>
		<category><![CDATA[기본 개념]]></category>
		<category><![CDATA[기초]]></category>
		<category><![CDATA[논리적 사고]]></category>
		<category><![CDATA[다이어그램]]></category>
		<category><![CDATA[단계별 설명]]></category>
		<category><![CDATA[단계별 진행]]></category>
		<category><![CDATA[대량 데이터]]></category>
		<category><![CDATA[대안 접근법]]></category>
		<category><![CDATA[데이터 구조]]></category>
		<category><![CDATA[데이터 스트림]]></category>
		<category><![CDATA[동생 게임]]></category>
		<category><![CDATA[동작 원리]]></category>
		<category><![CDATA[동적 데이터]]></category>
		<category><![CDATA[동적 중간값]]></category>
		<category><![CDATA[디자인 패턴]]></category>
		<category><![CDATA[로그 시간]]></category>
		<category><![CDATA[메모리 사용]]></category>
		<category><![CDATA[문제 분석]]></category>
		<category><![CDATA[문제 해결]]></category>
		<category><![CDATA[문제 해결력]]></category>
		<category><![CDATA[백준]]></category>
		<category><![CDATA[백준 1655]]></category>
		<category><![CDATA[백준 1655번]]></category>
		<category><![CDATA[백준이]]></category>
		<category><![CDATA[범위 제한]]></category>
		<category><![CDATA[복잡도 분석]]></category>
		<category><![CDATA[상세 설명]]></category>
		<category><![CDATA[상태 변화]]></category>
		<category><![CDATA[성능 개선]]></category>
		<category><![CDATA[성능 튜닝]]></category>
		<category><![CDATA[성능 평가]]></category>
		<category><![CDATA[소프트웨어 공학]]></category>
		<category><![CDATA[속도 개선]]></category>
		<category><![CDATA[수열 처리]]></category>
		<category><![CDATA[숫자 스트림]]></category>
		<category><![CDATA[스트리밍 알고리즘]]></category>
		<category><![CDATA[시각화]]></category>
		<category><![CDATA[시간 복잡도]]></category>
		<category><![CDATA[시간 효율성]]></category>
		<category><![CDATA[실시간 응용]]></category>
		<category><![CDATA[실시간 중간값]]></category>
		<category><![CDATA[실시간 처리]]></category>
		<category><![CDATA[실용적 구현]]></category>
		<category><![CDATA[실제 구현]]></category>
		<category><![CDATA[심화 학습]]></category>
		<category><![CDATA[알고리즘]]></category>
		<category><![CDATA[알고리즘 문제]]></category>
		<category><![CDATA[알고리즘 비교]]></category>
		<category><![CDATA[알고리즘 최적화]]></category>
		<category><![CDATA[알고리즘 패턴]]></category>
		<category><![CDATA[알고리즘 학습]]></category>
		<category><![CDATA[연속된 데이터]]></category>
		<category><![CDATA[연습 문제]]></category>
		<category><![CDATA[예외 상황]]></category>
		<category><![CDATA[예제 시뮬레이션]]></category>
		<category><![CDATA[온라인 알고리즘]]></category>
		<category><![CDATA[우선순위 큐]]></category>
		<category><![CDATA[우선순위 큐 활용]]></category>
		<category><![CDATA[음수 처리]]></category>
		<category><![CDATA[응용 기술]]></category>
		<category><![CDATA[이해하기 쉬운]]></category>
		<category><![CDATA[입력 처리]]></category>
		<category><![CDATA[자료구조 공부]]></category>
		<category><![CDATA[자료구조 선택]]></category>
		<category><![CDATA[자료구조 설계]]></category>
		<category><![CDATA[작은 값 선택]]></category>
		<category><![CDATA[접근 방법]]></category>
		<category><![CDATA[조건 처리]]></category>
		<category><![CDATA[주요 개념]]></category>
		<category><![CDATA[중간 위치]]></category>
		<category><![CDATA[중간값 계산]]></category>
		<category><![CDATA[중간값 유지]]></category>
		<category><![CDATA[중간값 찾기]]></category>
		<category><![CDATA[중앙값]]></category>
		<category><![CDATA[짝수 경우]]></category>
		<category><![CDATA[최대 힙]]></category>
		<category><![CDATA[최소 힙]]></category>
		<category><![CDATA[최적 해법]]></category>
		<category><![CDATA[최적화 기법]]></category>
		<category><![CDATA[출력 생성]]></category>
		<category><![CDATA[컴퓨터 과학]]></category>
		<category><![CDATA[코드 분석]]></category>
		<category><![CDATA[코드 예시]]></category>
		<category><![CDATA[코딩 기법]]></category>
		<category><![CDATA[코딩 테스트]]></category>
		<category><![CDATA[코딩테스트]]></category>
		<category><![CDATA[코테]]></category>
		<category><![CDATA[프로그래밍 스킬]]></category>
		<category><![CDATA[프로그래밍 연습]]></category>
		<category><![CDATA[프로그래밍 팁]]></category>
		<category><![CDATA[학습 포인트]]></category>
		<category><![CDATA[해결 전략]]></category>
		<category><![CDATA[핵심 아이디어]]></category>
		<category><![CDATA[효율성]]></category>
		<category><![CDATA[효율적 알고리즘]]></category>
		<category><![CDATA[효율적 처리]]></category>
		<category><![CDATA[효율적 코딩]]></category>
		<category><![CDATA[흐름도]]></category>
		<category><![CDATA[힙 균형]]></category>
		<category><![CDATA[힙 자료구조]]></category>
		<category><![CDATA[힙 크기 조정]]></category>
		<category><![CDATA[힙 활용]]></category>
		<guid isPermaLink="false">https://lycos7560.com/?p=40309</guid>

					<description><![CDATA[<p>가운데를 말해요 https://www.acmicpc.net/problem/1655 시간 제한 메모리 제한 제출 정답 맞힌 사람 정답 비율 0.1 초 128 MB 80245 24515 18393 31.195% 문제 백준이는 동생에게 &#8220;가운데를 말해요&#8221; 게임을 가르쳐주고 있다. 백준이가&#160;정수를 하나씩 외칠때마다 동생은 지금까지 백준이가 말한 수 중에서 중간값을 말해야 한다. 만약, 그동안 백준이가 외친 수의 개수가 짝수개라면 중간에 있는 두 수 중에서 작은 수를 [&#8230;]</p>
<p>The post <a href="https://lycos7560.com/cpp/%eb%b0%b1%ec%a4%80-1655%eb%b2%88-%ea%b0%80%ec%9a%b4%eb%8d%b0%eb%a5%bc-%eb%a7%90%ed%95%b4%ec%9a%94-c/40309/">백준 1655번 (가운데를 말해요, C++)</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></description>
										<content:encoded><![CDATA[				<div class="wp-block-uagb-table-of-contents uagb-toc__align-left uagb-toc__columns-1  uagb-block-87ca5ab3      "
					data-scroll= "1"
					data-offset= "30"
					style=""
				>
				<div class="uagb-toc__wrap">
						<div class="uagb-toc__title">
							목차						</div>
																						<div class="uagb-toc__list-wrap ">
						<ol class="uagb-toc__list"><li class="uagb-toc__list"><a href="#가운데를-말해요" class="uagb-toc-link__trigger">가운데를 말해요</a><ul class="uagb-toc__list"><li class="uagb-toc__list"><a href="#문제" class="uagb-toc-link__trigger">문제</a><li class="uagb-toc__list"><li class="uagb-toc__list"><a href="#입력" class="uagb-toc-link__trigger">입력</a><li class="uagb-toc__list"><li class="uagb-toc__list"><a href="#출력" class="uagb-toc-link__trigger">출력</a><li class="uagb-toc__list"><li class="uagb-toc__list"><a href="#예제-입력-1" class="uagb-toc-link__trigger">예제 입력 1</a><li class="uagb-toc__list"><li class="uagb-toc__list"><a href="#예제-출력-1" class="uagb-toc-link__trigger">예제 출력 1</a><li class="uagb-toc__list"><li class="uagb-toc__list"><a href="#출처" class="uagb-toc-link__trigger">출처</a><li class="uagb-toc__list"><li class="uagb-toc__list"><a href="#알고리즘-분류" class="uagb-toc-link__trigger">알고리즘 분류</a><li class="uagb-toc__list"><li class="uagb-toc__list"><a href="#1차-시도-배열-인덱스-실패-시간-초과" class="uagb-toc-link__trigger">1차 시도 &#8211; 배열 인덱스 (실패 / 시간 초과)</a><li class="uagb-toc__list"><li class="uagb-toc__list"><a href="#2차-시도-two-heaps-방식-성공" class="uagb-toc-link__trigger">2차 시도 &#8211; Two Heaps 방식 (성공)</a></ul></ol>					</div>
									</div>
				</div>
			


<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">가운데를 말해요 <img decoding="async" width="35" height="45" class="wp-image-37903" style="width: 35px;" src="https://lycos7560.com/wp-content/uploads/2024/03/Gold_2.jpg" alt="" srcset="https://lycos7560.com/wp-content/uploads/2024/03/Gold_2.jpg 400w, https://lycos7560.com/wp-content/uploads/2024/03/Gold_2-234x300.jpg 234w" sizes="(max-width: 35px) 100vw, 35px" /></h2>



<p class="wp-block-paragraph"><a href="https://www.acmicpc.net/problem/1655" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problem/1655</a></p>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>시간 제한</th><th>메모리 제한</th><th>제출</th><th>정답</th><th>맞힌 사람</th><th>정답 비율</th></tr></thead><tbody><tr><td>0.1 초</td><td>128 MB</td><td>80245</td><td>24515</td><td>18393</td><td>31.195%</td></tr></tbody></table></figure>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">문제</h3>



<p class="wp-block-paragraph">백준이는 동생에게 &#8220;가운데를 말해요&#8221; 게임을 가르쳐주고 있다. </p>



<p class="wp-block-paragraph">백준이가&nbsp;정수를 하나씩 외칠때마다 동생은 지금까지 백준이가 말한 수 중에서 중간값을 말해야 한다. </p>



<p class="wp-block-paragraph">만약, 그동안 백준이가 외친 수의 개수가 짝수개라면 중간에 있는 두 수 중에서 작은 수를 말해야 한다.</p>



<p class="wp-block-paragraph">예를 들어 백준이가 동생에게 1, 5, 2, 10, -99, 7, 5를 순서대로 외쳤다고 하면, 동생은 1, 1, 2, 2, 2, 2, 5를 차례대로 말해야 한다. </p>



<p class="wp-block-paragraph">백준이가 외치는 수가 주어졌을 때, 동생이 말해야 하는 수를 구하는 프로그램을 작성하시오.</p>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">입력</h3>



<p class="wp-block-paragraph">첫째 줄에는 백준이가 외치는 정수의 개수 N이 주어진다. </p>



<p class="wp-block-paragraph">N은 1보다 크거나 같고, 100,000보다 작거나 같은 자연수이다. </p>



<p class="wp-block-paragraph">그 다음 N줄에 걸쳐서 백준이가 외치는 정수가 차례대로 주어진다. </p>



<p class="wp-block-paragraph">정수는 -10,000보다 크거나 같고, 10,000보다 작거나 같다.</p>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">출력</h3>



<p class="wp-block-paragraph">한 줄에 하나씩 N줄에 걸쳐 백준이의 동생이 말해야 하는 수를 순서대로 출력한다.</p>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">예제 입력 1</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">7
1
5
2
10
-99
7
5</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">예제 출력 1</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1
1
2
2
2
2
5</pre>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">출처</h3>



<ul class="wp-block-list">
<li>문제를 만든 사람:&nbsp;<a href="https://www.acmicpc.net/user/ntopia" target="_blank" rel="noreferrer noopener">ntopia</a></li>



<li>데이터를 추가한 사람:&nbsp;<a href="https://www.acmicpc.net/user/pichulia" target="_blank" rel="noreferrer noopener">pichulia</a></li>



<li>문제를 각색한 사람:&nbsp;<a href="https://www.acmicpc.net/user/baekjoon" target="_blank" rel="noreferrer noopener">baekjoon</a></li>
</ul>



<div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div>



<h3 class="wp-block-heading">알고리즘 분류</h3>



<ul class="wp-block-list">
<li><a href="https://www.acmicpc.net/problem/tag/175" target="_blank" rel="noreferrer noopener">자료 구조</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/59" target="_blank" rel="noreferrer noopener">우선순위 큐</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-wide" style="margin-top:var(--wp--preset--spacing--70);margin-bottom:var(--wp--preset--spacing--70)"/>



<h3 class="wp-block-heading">1차 시도 &#8211; 배열 인덱스 (실패 / 시간 초과)</h3>



<figure class="wp-block-image size-full"><img decoding="async" width="1041" height="34" src="https://lycos7560.com/wp-content/uploads/2025/10/image-1.png" alt="" class="wp-image-40311" srcset="https://lycos7560.com/wp-content/uploads/2025/10/image-1.png 1041w, https://lycos7560.com/wp-content/uploads/2025/10/image-1-300x10.png 300w, https://lycos7560.com/wp-content/uploads/2025/10/image-1-768x25.png 768w" sizes="(max-width: 1041px) 100vw, 1041px" /></figure>



<p class="wp-block-paragraph">배열을 기반으로, 중간값의 인덱스(<code>currentMedian</code>)를 유지하면서 새로운 값이 들어올 때마다 <code>leftCount</code>, <code>rightCount</code>를 조정하는 방식</p>



<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#include &lt;iostream>
using namespace std;

int n = 0;
int num[20001] = { 0 };  // 값의 출현 횟수 (index = value + 10000)
int currentMedian = 0;   // 현재 중간값의 인덱스
int leftCount = 0;       // 중간값보다 작은 값들의 개수
int rightCount = 0;      // 중간값보다 큰 값들의 개수

// 실제 값 => 배열 인덱스로 변환
inline int GetIndex(int value) 
{
    return value + 10000;
}

// 배열 인덱스 => 실제 값으로 변환
inline int GetValue(int index) 
{
    return index - 10000;
}

int FindMedianOptimized(int newValue, int total)
{
    int newIdx = GetIndex(newValue);
    num[newIdx]++;

    // 새 값의 위치에 따라 좌우 카운트 조정
    if (newIdx &lt; currentMedian) leftCount++;
    else if (newIdx > currentMedian) rightCount++;
    else rightCount++; // 같은 값일 경우 간단히 오른쪽으로 분류

    // 목표 중간 위치 계산
    int targetPos = (total + 1) / 2;

    // 중간값 인덱스를 왼쪽으로 이동 (왼쪽 원소가 너무 많을 때)
    while (leftCount >= targetPos) {
        currentMedian--;
        leftCount -= num[currentMedian];
        rightCount += num[currentMedian];
    }

    // 중간값 인덱스를 오른쪽으로 이동 (왼쪽 원소가 부족할 때)
    while (leftCount + num[currentMedian] &lt; targetPos) {
        leftCount += num[currentMedian];
        currentMedian++;
        rightCount -= num[currentMedian];
    }

    // 현재 중간값 반환
    return GetValue(currentMedian);
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    cin >> n;
    int value = 0;

    // 첫 번째 입력값으로 초기화
    cin >> value;
    num[GetIndex(value)]++;
    currentMedian = GetIndex(value);
    leftCount = 0;
    rightCount = 0;

    // 첫 번째 값 => 중간값
    cout &lt;&lt; value &lt;&lt; "\n"; 

    for (int i = 2; i &lt;= n; ++i) 
    {
        cin >> value;
        cout &lt;&lt; FindMedianOptimized(value, i) &lt;&lt; "\n";
    }

    return 0;
}
</pre>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<h4 class="wp-block-heading">시간 초과의 원인</h4>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="610" height="311" src="https://lycos7560.com/wp-content/uploads/2025/10/image-2.png" alt="" class="wp-image-40312" srcset="https://lycos7560.com/wp-content/uploads/2025/10/image-2.png 610w, https://lycos7560.com/wp-content/uploads/2025/10/image-2-300x153.png 300w" sizes="(max-width: 610px) 100vw, 610px" /></figure>



<p class="wp-block-paragraph">새로운 값이 입력될 때마다 <strong><code>currentMedian</code>을 1씩 이동</strong>하며 왼쪽/오른쪽 카운트를 갱신</p>



<p class="wp-block-paragraph"><code>currentMedian</code>의 이동 거리는 <strong>입력된 값의 분포에 따라서</strong> 문제가 생길 수 있음.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// 최악의 경우
-10000, -9999, -9998, ... , 9999, 10000
</pre>



<div style="height:5px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="wp-block-paragraph">매번 새로운 값이 들어올 때마다 <code>currentMedian</code>이 <strong>오른쪽 끝으로 한 칸씩 이동</strong></p>



<p class="wp-block-paragraph">매번 <code>while</code> 루프가 <strong>최대 20,000번 반복</strong>되는 불상사가 생길 수 있음</p>



<p class="wp-block-paragraph">입력 n = 100,000일 때 <strong>최악의 복잡도: <code>O(n * 20000)</code> = 2,000,000,000 (20억)</strong> </p>



<p class="wp-block-paragraph"><code>currentMedian</code> 부분을 개선 또는 다른 알고리즘을 사용하는 방법이 더 좋아보임</p>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-wide" style="margin-top:var(--wp--preset--spacing--70);margin-bottom:var(--wp--preset--spacing--70)"/>



<h3 class="wp-block-heading">2차 시도 &#8211; Two Heaps 방식 (성공)</h3>



<figure class="wp-block-image size-full"><img decoding="async" width="1044" height="42" src="https://lycos7560.com/wp-content/uploads/2025/10/image.png" alt="" class="wp-image-40310" srcset="https://lycos7560.com/wp-content/uploads/2025/10/image.png 1044w, https://lycos7560.com/wp-content/uploads/2025/10/image-300x12.png 300w, https://lycos7560.com/wp-content/uploads/2025/10/image-768x31.png 768w" sizes="(max-width: 1044px) 100vw, 1044px" /></figure>



<p class="wp-block-paragraph"><code>maxHeap</code>(왼쪽) + <code>minHeap</code>(오른쪽)으로 균형 유지</p>



<p class="wp-block-paragraph"><code>maxHeap</code>: 중간값 이하의 값들 저장 (왼쪽 절반)</p>



<p class="wp-block-paragraph"><code>minHeap</code>: 중간값 이상의 값들 저장 (오른쪽 절반)</p>



<p class="wp-block-paragraph">균형 조정 시 힙에서 한 번씩 <code>push/pop</code> → <code>O(log n)</code></p>



<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#include &lt;iostream>
#include &lt;queue>
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int n;
    cin >> n;

    priority_queue&lt;int> maxHeap;                            // 왼쪽 절반 (최대 힙)
    priority_queue&lt;int, vector&lt;int>, greater&lt;int>> minHeap;  // 오른쪽 절반 (최소 힙)

    for (int i = 0; i &lt; n; ++i) 
    {
        int value;
        cin >> value;

        // 값 삽입: 왼쪽/오른쪽 균형 유지
        if (maxHeap.empty() || value &lt;= maxHeap.top())
            maxHeap.push(value);
        else
            minHeap.push(value);

        // 두 힙의 크기 균형 조정 (왼쪽 = 오른쪽 또는 +1)
        if (maxHeap.size() > minHeap.size() + 1) {
            minHeap.push(maxHeap.top());
            maxHeap.pop();
        }
        else if (minHeap.size() > maxHeap.size()) {
            maxHeap.push(minHeap.top());
            minHeap.pop();
        }

        // 현재 중간값 출력
        cout &lt;&lt; maxHeap.top() &lt;&lt; "\n";
    }

    return 0;
}
</pre>



<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">입력: [1, 5, 2, 10, -5, 8, 3]

단계별 힙 상태:

1. value=1
   maxHeap: [1]      minHeap: []
   중간값: 1

2. value=5
   maxHeap: [1]      minHeap: [5]
   중간값: 1

3. value=2
   maxHeap: [2, 1]   minHeap: [5]
   중간값: 2

4. value=10
   maxHeap: [2, 1]   minHeap: [5, 10]
   중간값: 2

5. value=-5
   maxHeap: [2, 1, -5] minHeap: [5, 10]
   중간값: 2

6. value=8
   maxHeap: [2, 1, -5] minHeap: [5, 8, 10]
   중간값: 2

7. value=3
   maxHeap: [3, 2, -5, 1] minHeap: [5, 8, 10]
   중간값: 3</pre>
<p>The post <a href="https://lycos7560.com/cpp/%eb%b0%b1%ec%a4%80-1655%eb%b2%88-%ea%b0%80%ec%9a%b4%eb%8d%b0%eb%a5%bc-%eb%a7%90%ed%95%b4%ec%9a%94-c/40309/">백준 1655번 (가운데를 말해요, C++)</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://lycos7560.com/cpp/%eb%b0%b1%ec%a4%80-1655%eb%b2%88-%ea%b0%80%ec%9a%b4%eb%8d%b0%eb%a5%bc-%eb%a7%90%ed%95%b4%ec%9a%94-c/40309/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>백준 2108번 (통계학, C++) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/2108-statistics-c-binarysearch-baekjoon/4578/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/2108-statistics-c-binarysearch-baekjoon/4578/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Sun, 15 Jan 2023 20:33:09 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[2108]]></category>
		<category><![CDATA[2108번]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[study]]></category>
		<category><![CDATA[공부]]></category>
		<category><![CDATA[구현]]></category>
		<category><![CDATA[기본]]></category>
		<category><![CDATA[기초]]></category>
		<category><![CDATA[백준]]></category>
		<category><![CDATA[백준 2108]]></category>
		<category><![CDATA[백준 2108번]]></category>
		<category><![CDATA[범위]]></category>
		<category><![CDATA[산술평균]]></category>
		<category><![CDATA[수학]]></category>
		<category><![CDATA[알고리즘]]></category>
		<category><![CDATA[정렬]]></category>
		<category><![CDATA[중앙값]]></category>
		<category><![CDATA[최빈값]]></category>
		<category><![CDATA[코딩테스트]]></category>
		<category><![CDATA[코테]]></category>
		<category><![CDATA[통계학]]></category>
		<guid isPermaLink="false">https://lycos7560.com/?p=4578</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 2108번 "통계학" 문제에 대한 글입니다. (This article is about the "Statistics" problem in BAEKJOON No. 2108.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/2108-statistics-c-binarysearch-baekjoon/4578/">백준 2108번 (통계학, C++) [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5698326622209671" crossorigin="anonymous"></script>
<!-- HorizontalAD -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-5698326622209671" data-ad-slot="6908948342" data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>



<div style="height:62px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">통계학</h2>



<p class="has-medium-font-size wp-block-paragraph"><a href="https://www.acmicpc.net/problem/2108">https://www.acmicpc.net/problem/2108</a></p>



<div style="height:41px" aria-hidden="true" class="wp-block-spacer"></div>



<figure id="problem-info" class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th class="has-text-align-left" data-align="left">시간 제한</th><th class="has-text-align-left" data-align="left">메모리 제한</th><th class="has-text-align-left" data-align="left">제출</th><th class="has-text-align-left" data-align="left">정답</th><th class="has-text-align-left" data-align="left">맞힌 사람</th><th class="has-text-align-left" data-align="left">정답 비율</th></tr></thead><tbody><tr><td class="has-text-align-left" data-align="left">2 초</td><td class="has-text-align-left" data-align="left">256 MB</td><td class="has-text-align-left" data-align="left">124496</td><td class="has-text-align-left" data-align="left">27685</td><td class="has-text-align-left" data-align="left">22260</td><td class="has-text-align-left" data-align="left">25.422%</td></tr></tbody></table></figure>



<div style="height:44px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">문제</h2>



<p class="has-medium-font-size wp-block-paragraph">수를 처리하는 것은 통계학에서 상당히 중요한 일이다. </p>



<p class="has-medium-font-size wp-block-paragraph">통계학에서 N개의 수를 대표하는 기본 통계 값에는 다음과 같은 것들이 있다. </p>



<p class="has-medium-font-size wp-block-paragraph">단, N은 홀수라고 가정하자.</p>



<div style="height:35px" aria-hidden="true" class="wp-block-spacer"></div>



<ol class="wp-block-list">
<li>산술평균 : N개의 수들의 합을 N으로 나눈 값</li>



<li>중앙값 : N개의 수들을 증가하는 순서로 나열했을 경우 그 중앙에 위치하는 값</li>



<li>최빈값 : N개의 수들 중 가장 많이 나타나는 값</li>



<li>범위 : N개의 수들 중 최댓값과 최솟값의 차이</li>
</ol>



<div style="height:32px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph">N개의 수가 주어졌을 때, </p>



<p class="has-medium-font-size wp-block-paragraph">네 가지 기본 통계값을 구하는 프로그램을 작성하시오.</p>



<div style="height:58px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">입력</h2>



<p class="has-medium-font-size wp-block-paragraph">첫째 줄에 수의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">단, N은 홀수이다. 그 다음 N개의 줄에는 정수들이 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">입력되는 정수의 절댓값은 4,000을 넘지 않는다.</p>



<div style="height:42px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">출력</h2>



<p class="has-medium-font-size wp-block-paragraph">첫째 줄에는 산술평균을 출력한다. </p>



<p class="has-medium-font-size wp-block-paragraph">소수점 이하 첫째 자리에서 반올림한 값을 출력한다.</p>



<p class="has-medium-font-size wp-block-paragraph">둘째 줄에는 중앙값을 출력한다.</p>



<p class="has-medium-font-size wp-block-paragraph">셋째 줄에는 최빈값을 출력한다. </p>



<p class="has-medium-font-size wp-block-paragraph">여러 개 있을 때에는 최빈값 중 두 번째로 작은 값을 출력한다.</p>



<p class="has-medium-font-size wp-block-paragraph">넷째 줄에는 범위를 출력한다.</p>



<h2 class="wp-block-heading">예제 입력 1</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5
1
3
8
-2
2</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 1</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">2
2
1
10</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 2</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1
4000</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 2</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">4000
4000
4000
0</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 3</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5
-1
-2
-3
-1
-2</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 3</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">-2
-2
-1
2</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 입력 4</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">3
0
0
-1</pre>



<div style="height:31px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">예제 출력 4</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0
0
0
1</pre>



<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>



<p class="has-medium-font-size wp-block-paragraph">(0 + 0 + (-1)) / 3 = -0.333333&#8230; 이고 이를 첫째 자리에서 반올림하면 0이다. -0으로 출력하면 안된다.</p>



<div style="height:44px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">출처</h2>



<ul class="wp-block-list">
<li>데이터를 추가한 사람: <a href="https://www.acmicpc.net/user/bjh3502" target="_blank" rel="noreferrer noopener">bjh3502</a>, <a href="https://www.acmicpc.net/user/bsyun0571" target="_blank" rel="noreferrer noopener">bsyun0571</a>, <a href="https://www.acmicpc.net/user/djm03178" target="_blank" rel="noreferrer noopener">djm03178</a>, <a href="https://www.acmicpc.net/user/jungyh1509" target="_blank" rel="noreferrer noopener">jungyh1509</a>, <a href="https://www.acmicpc.net/user/palilo" target="_blank" rel="noreferrer noopener">palilo</a>, <a href="https://www.acmicpc.net/user/YunGoon" target="_blank" rel="noreferrer noopener">YunGoon</a></li>



<li>문제의 오타를 찾은 사람: <a href="https://www.acmicpc.net/user/jh05013" target="_blank" rel="noreferrer noopener">jh05013</a>, <a href="https://www.acmicpc.net/user/skynet">s</a><a href="https://www.acmicpc.net/user/skynet" target="_blank" rel="noreferrer noopener">k</a><a href="https://www.acmicpc.net/user/skynet">ynet</a></li>
</ul>



<div style="height:44px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">알고리즘 분류</h2>



<ul class="wp-block-list">
<li><a href="https://www.acmicpc.net/problem/tag/124" target="_blank" rel="noreferrer noopener">수학</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/102" target="_blank" rel="noreferrer noopener">구현</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/97" target="_blank" rel="noreferrer noopener">정렬</a></li>
</ul>



<div style="height:37px" aria-hidden="true" class="wp-block-spacer"></div>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-wide" style="margin-top:var(--wp--preset--spacing--80);margin-bottom:var(--wp--preset--spacing--80)"/>



<p class="has-medium-font-size wp-block-paragraph">최빈값이 여러 개 있을 때에는 최빈값 중 두 번째로 작은 값을 출력하는 부분을 구현하느냐고 엄청 시간이 걸렸다.</p>



<p class="has-medium-font-size wp-block-paragraph">최빈값이 같으면 리스트에 넣어서 순서를 계산하는 방식으로 처리했다.</p>



<div style="height:38px" aria-hidden="true" class="wp-block-spacer"></div>



<h2 class="wp-block-heading">통과된 코드</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="cpp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#include &lt;iostream>
#include &lt;list>
#include &lt;algorithm>
#include &lt;cmath>
#include &lt;set>

using namespace std;

int N, tempI, tempK, temp, tempJ;
int arr[500001];
int number[8001];
long long int sumAll;
list&lt;float> myList; // 결과를 저장할 리스트
list&lt;float> myList2; 

int main()
{
	ios_base::sync_with_stdio(false); // scanf와 동기화를 비활성화
	// cin.tie(null); 코드는 cin과 cout의 묶음을 풀어줍니다.
	cin.tie(NULL);
	cout.tie(NULL);
	sumAll = 0;

	cin >> N;
	for (int i = 0; i &lt; N; i++) {
		cin >> arr[i]; // N만큼 입력을 받음
		if (arr[i] > 0) number[arr[i] + 4000]++; // 양수일 경우
		else number[arr[i] * -1]++;
	}
		
	for (int i = 0; i &lt; N; i++)  // 총합을 구함
		sumAll = sumAll + arr[i];

	// 1. 산술평균 : N개의 수들의 합을 N으로 나눈 값
	float tempN = sumAll;
	myList.push_back(floor((tempN / N) + 0.5));

	// 2. 중앙값 : N개의 수들을 증가하는 순서로 나열했을 경우 그 중앙에 위치하는 값
	sort(arr, arr + N); // 오름차순 정렬

	myList.push_back(arr[(0 + (N))/2]);

	// 3. 최빈값 : N개의 수들 중 가장 많이 나타나는 값
	tempK = 0, tempI = -9999, tempJ = 0;
	int first = 0, second = 0;
	for (int i = 0; i &lt; 8001; i++) {
		if (i &lt;= 4000) {
			if (number[i] > tempI ) {
				tempI = number[i];
				tempK = i * -1;
				myList2.clear();
				myList2.push_back(tempK);
			}
			else if (number[i] == tempI) {
				tempK = i * -1;
				myList2.push_back(tempK);
			}
		}
		else {
				if (number[i] > tempI) {
					tempI = number[i];
					tempN = i - 4000;
					myList2.clear();
					myList2.push_back(tempN);
				}
				else if (number[i] == tempI) {
					tempK = i - 4000;
					myList2.push_back(tempK);
				}
		}
	}

	myList2.sort();

	int size = myList2.size();
	int cnt = 0;

	if (size >= 2) cnt = 2;
	else cnt = 1;

	for (auto it = myList2.begin(); it != myList2.end(); it++) {
		cnt--;
		if (cnt == 0) {
			myList.push_back(*it);
			break;
		}
	}

	// 4. 범위 : N개의 수들 중 최댓값과 최솟값의 차이
	temp = arr[0] - arr[N-1];
	temp = abs(temp);
	myList.push_back(temp);


	// 결과를 출력합니다.
	for (auto it = myList.begin(); it != myList.end(); it++) {
		cout &lt;&lt; *it &lt;&lt; "\n";
	}

	return 0;
}</pre>



<div style="height:34px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image size-full"><img decoding="async" width="1040" height="97" src="https://lycos7560.com/wp-content/uploads/image-941.png" alt="" class="wp-image-4580" srcset="https://lycos7560.com/wp-content/uploads/image-941.png 1040w, https://lycos7560.com/wp-content/uploads/image-941-300x28.png 300w, https://lycos7560.com/wp-content/uploads/image-941-768x72.png 768w" sizes="(max-width: 1040px) 100vw, 1040px" /></figure>



<div style="height:35px" aria-hidden="true" class="wp-block-spacer"></div>



<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5698326622209671" crossorigin="anonymous"></script>
<ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5698326622209671" data-ad-slot="4245812909"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/2108-statistics-c-binarysearch-baekjoon/4578/">백준 2108번 (통계학, C++) [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://lycos7560.com/cpp/baekjoon_online_judge/2108-statistics-c-binarysearch-baekjoon/4578/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
