<?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/%EB%B0%B0%EC%97%B4/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>생각의 흐름을 타고 다니며 만드는 블로그</description>
	<lastBuildDate>Mon, 13 Oct 2025 06:07:16 +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>백준 14003번 (가장 긴 증가하는 부분 수열 5, C++)</title>
		<link>https://lycos7560.com/cpp/%eb%b0%b1%ec%a4%80-14003%eb%b2%88-%ea%b0%80%ec%9e%a5-%ea%b8%b4-%ec%a6%9d%ea%b0%80%ed%95%98%eb%8a%94-%eb%b6%80%eb%b6%84-%ec%88%98%ec%97%b4-5-c/40314/</link>
					<comments>https://lycos7560.com/cpp/%eb%b0%b1%ec%a4%80-14003%eb%b2%88-%ea%b0%80%ec%9e%a5-%ea%b8%b4-%ec%a6%9d%ea%b0%80%ed%95%98%eb%8a%94-%eb%b6%80%eb%b6%84-%ec%88%98%ec%97%b4-5-c/40314/#comments</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Mon, 13 Oct 2025 06:06:17 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[14003]]></category>
		<category><![CDATA[14003번]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[Algorithm Analysis]]></category>
		<category><![CDATA[Algorithm Explanation]]></category>
		<category><![CDATA[Algorithm Practice]]></category>
		<category><![CDATA[Algorithm Study]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[Binary Search LIS]]></category>
		<category><![CDATA[binary_search]]></category>
		<category><![CDATA[BOJ 14003]]></category>
		<category><![CDATA[BOJ Solution]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[C++ Algorithm]]></category>
		<category><![CDATA[C++ STL]]></category>
		<category><![CDATA[Coding Interview]]></category>
		<category><![CDATA[Coding Lecture]]></category>
		<category><![CDATA[Coding Test]]></category>
		<category><![CDATA[Competitive Coding]]></category>
		<category><![CDATA[Competitive Programming]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[DP]]></category>
		<category><![CDATA[DP Table]]></category>
		<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Efficiency]]></category>
		<category><![CDATA[Example Walkthrough]]></category>
		<category><![CDATA[Fast IO]]></category>
		<category><![CDATA[Greedy]]></category>
		<category><![CDATA[Greedy Algorithm]]></category>
		<category><![CDATA[Implementation]]></category>
		<category><![CDATA[Increasing Sequence]]></category>
		<category><![CDATA[Index Mapping]]></category>
		<category><![CDATA[Index Tracking]]></category>
		<category><![CDATA[Input Output]]></category>
		<category><![CDATA[LIS]]></category>
		<category><![CDATA[LIS Diagram]]></category>
		<category><![CDATA[LIS Example]]></category>
		<category><![CDATA[LIS Flow]]></category>
		<category><![CDATA[LIS Indexing]]></category>
		<category><![CDATA[LIS Pattern]]></category>
		<category><![CDATA[LIS Reconstruction]]></category>
		<category><![CDATA[LIS Reconstruction Algorithm]]></category>
		<category><![CDATA[LIS step by step]]></category>
		<category><![CDATA[LIS Study]]></category>
		<category><![CDATA[LIS Table]]></category>
		<category><![CDATA[LIS Tail]]></category>
		<category><![CDATA[LIS Track]]></category>
		<category><![CDATA[LIS Tutorial]]></category>
		<category><![CDATA[LIS using Binary Search]]></category>
		<category><![CDATA[LIS Visualization]]></category>
		<category><![CDATA[LIS 강의]]></category>
		<category><![CDATA[LIS 구현]]></category>
		<category><![CDATA[LIS 단계별]]></category>
		<category><![CDATA[LIS 문제]]></category>
		<category><![CDATA[LIS 문제풀이]]></category>
		<category><![CDATA[LIS 복원]]></category>
		<category><![CDATA[LIS 복원 알고리즘]]></category>
		<category><![CDATA[LIS 알고리즘]]></category>
		<category><![CDATA[LIS 예제]]></category>
		<category><![CDATA[LIS 추적]]></category>
		<category><![CDATA[LIS 코드]]></category>
		<category><![CDATA[LIS 패턴]]></category>
		<category><![CDATA[Logic Explanation]]></category>
		<category><![CDATA[Longest Increasing Subsequence]]></category>
		<category><![CDATA[Longest Subsequence]]></category>
		<category><![CDATA[lower_bound]]></category>
		<category><![CDATA[Memory Limit]]></category>
		<category><![CDATA[Memory Optimization]]></category>
		<category><![CDATA[O(N log N)]]></category>
		<category><![CDATA[O(N^2)]]></category>
		<category><![CDATA[O(NlogN)]]></category>
		<category><![CDATA[Optimal Algorithm]]></category>
		<category><![CDATA[Optimization]]></category>
		<category><![CDATA[Prev Index]]></category>
		<category><![CDATA[Problem Explanation]]></category>
		<category><![CDATA[problem solving]]></category>
		<category><![CDATA[Programming Algorithm]]></category>
		<category><![CDATA[Programming Study]]></category>
		<category><![CDATA[Sequence Analysis]]></category>
		<category><![CDATA[Sequence Optimization]]></category>
		<category><![CDATA[Sequence Problem]]></category>
		<category><![CDATA[Sequence Reconstruction]]></category>
		<category><![CDATA[Sequence Trace]]></category>
		<category><![CDATA[STL]]></category>
		<category><![CDATA[study]]></category>
		<category><![CDATA[Subsequence]]></category>
		<category><![CDATA[Tail Array]]></category>
		<category><![CDATA[Theory]]></category>
		<category><![CDATA[Time Complexity]]></category>
		<category><![CDATA[Time Limit]]></category>
		<category><![CDATA[Traceback]]></category>
		<category><![CDATA[upper_bound]]></category>
		<category><![CDATA[vector]]></category>
		<category><![CDATA[가장 긴 증가하는 부분 수열]]></category>
		<category><![CDATA[가장 긴 증가하는 부분 수열 5]]></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[백준 14003]]></category>
		<category><![CDATA[백준 14003번]]></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[인덱스 기반 LIS]]></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=40314</guid>

					<description><![CDATA[<p>가장 긴 증가하는 부분 수열 5 https://www.acmicpc.net/problem/14003 시간 제한 메모리 제한 제출 정답 맞힌 사람 정답 비율 3 초 512 MB 45574 15974 11322 34.533% 문제 수열 A가 주어졌을 때, 가장 긴 증가하는&#160;부분&#160;수열을 구하는 프로그램을 작성하시오. 예를 들어, 수열 A = {10, 20, 10, 30, 20, 50} 인 경우에 가장 긴 증가하는 부분&#160;수열은&#160;A = {10,&#160;20, [&#8230;]</p>
<p>The post <a href="https://lycos7560.com/cpp/%eb%b0%b1%ec%a4%80-14003%eb%b2%88-%ea%b0%80%ec%9e%a5-%ea%b8%b4-%ec%a6%9d%ea%b0%80%ed%95%98%eb%8a%94-%eb%b6%80%eb%b6%84-%ec%88%98%ec%97%b4-5-c/40314/">백준 14003번 (가장 긴 증가하는 부분 수열 5, 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="#가장-긴-증가하는-부분-수열-5" class="uagb-toc-link__trigger">가장 긴 증가하는 부분 수열 5</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="#알고리즘-분류" 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차-시도-이분-탐색-인덱스-추적을-이용한-lis-복원-on-log-n" class="uagb-toc-link__trigger">2차 시도 &#8211; 이분 탐색 + 인덱스 추적을 이용한 LIS 복원 / O(N log N)</a></ul></ol>					</div>
									</div>
				</div>
			


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



<h2 class="wp-block-heading">가장 긴 증가하는 부분 수열 5 <img decoding="async" width="35" height="45" class="wp-image-37909" style="width: 35px;" src="https://lycos7560.com/wp-content/uploads/2024/03/Platinum_5.jpg" alt="" srcset="https://lycos7560.com/wp-content/uploads/2024/03/Platinum_5.jpg 400w, https://lycos7560.com/wp-content/uploads/2024/03/Platinum_5-234x300.jpg 234w" sizes="(max-width: 35px) 100vw, 35px" /></h2>



<p class="wp-block-paragraph"><a href="https://www.acmicpc.net/problem/14003" target="_blank" rel="noreferrer noopener">https://www.acmicpc.net/problem/14003</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>3 초</td><td>512 MB</td><td>45574</td><td>15974</td><td>11322</td><td>34.533%</td></tr></tbody></table></figure>



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



<p class="wp-block-paragraph">수열 A가 주어졌을 때, 가장 긴 증가하는&nbsp;부분&nbsp;수열을 구하는 프로그램을 작성하시오.</p>



<p class="wp-block-paragraph">예를 들어, 수열 A = {10, 20, 10, 30, 20, 50} 인 경우에 가장 긴 증가하는 부분&nbsp;수열은&nbsp;A = {<strong>10</strong>,&nbsp;<strong>20</strong>, 10,&nbsp;<strong>30</strong>, 20,&nbsp;<strong>50</strong>} 이고, 길이는 4이다.</p>



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



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



<p class="wp-block-paragraph">첫째 줄에 수열 A의 크기 N (1 ≤ N ≤ 1,000,000)이 주어진다.</p>



<p class="wp-block-paragraph">둘째 줄에는 수열 A를 이루고 있는 A<sub>i</sub>가 주어진다. (-1,000,000,000&nbsp;≤ A<sub>i</sub>&nbsp;≤ 1,000,000,000)</p>



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



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



<p class="wp-block-paragraph">첫째 줄에 수열 A의 가장 긴 증가하는 부분 수열의 길이를 출력한다.</p>



<p class="wp-block-paragraph">둘째 줄에는 정답이 될 수 있는 가장 긴 증가하는 부분 수열을 출력한다.</p>



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



<div class="wp-block-uagb-container uagb-block-aa78ee06 alignfull uagb-is-root-container"><div class="uagb-container-inner-blocks-wrap">
<div class="wp-block-uagb-container uagb-block-70c24c24">
<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="">6
10 20 10 30 20 50</pre>
</div>



<div class="wp-block-uagb-container uagb-block-2c88bb50">
<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="">4
10 20 30 50</pre>
</div>
</div></div>



<div style="height:15px" 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/user/baekjoon">baekjoon</a></li>



<li>데이터를 추가한 사람: <a href="https://www.acmicpc.net/user/harinboy">harinboy</a>, <a href="https://www.acmicpc.net/user/jh05013">jh05013</a>, <a href="https://www.acmicpc.net/user/kkw564">kkw564</a>, <a href="https://www.acmicpc.net/user/ldw0318">ldw0318</a>, <a href="https://www.acmicpc.net/user/minho6428">minho6428</a>, <a href="https://www.acmicpc.net/user/sohnryang">sohnryang</a>, <a href="https://www.acmicpc.net/user/surung9898">surung9898</a>, <a href="https://www.acmicpc.net/user/yeo2507">yeo2507</a></li>



<li>빠진 조건을 찾은 사람: <a href="https://www.acmicpc.net/user/Acka">Acka</a></li>
</ul>



<div style="height:15px" 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/11053" target="_blank" rel="noreferrer noopener">11053번. 가장 긴 증가하는 부분 수열</a></li>



<li><a href="https://www.acmicpc.net/problem/11054" target="_blank" rel="noreferrer noopener">11054번. 가장 긴 바이토닉 부분 수열</a></li>



<li><a href="https://www.acmicpc.net/problem/11055" target="_blank" rel="noreferrer noopener">11055번. 가장 큰 증가하는 부분 수열</a></li>



<li><a href="https://www.acmicpc.net/problem/11722" target="_blank" rel="noreferrer noopener">11722번. 가장 긴 감소하는 부분 수열</a></li>



<li><a href="https://www.acmicpc.net/problem/12015" target="_blank" rel="noreferrer noopener">12015번. 가장 긴 증가하는 부분 수열 2</a></li>



<li><a href="https://www.acmicpc.net/problem/12738" target="_blank" rel="noreferrer noopener">12738번. 가장 긴 증가하는 부분 수열 3</a></li>



<li><a href="https://www.acmicpc.net/problem/14002" target="_blank" rel="noreferrer noopener">14002번. 가장 긴 증가하는 부분 수열 4</a></li>
</ul>



<div style="height:15px" 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/12" target="_blank" rel="noreferrer noopener">이분 탐색</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/235" target="_blank" rel="noreferrer noopener">역추적</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/43" 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--60);margin-bottom:var(--wp--preset--spacing--60)"/>



<h3 class="wp-block-heading">1차 시도 &#8211; 로직 그대로 구현</h3>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="1043" height="115" src="https://lycos7560.com/wp-content/uploads/2025/10/image-4.png" alt="" class="wp-image-40317" srcset="https://lycos7560.com/wp-content/uploads/2025/10/image-4.png 1043w, https://lycos7560.com/wp-content/uploads/2025/10/image-4-300x33.png 300w, https://lycos7560.com/wp-content/uploads/2025/10/image-4-768x85.png 768w" sizes="(max-width: 1043px) 100vw, 1043px" /></figure>



<p class="wp-block-paragraph">한 번의 입력(<code>num</code>)에 의해 생성된 새로운 시퀀스들을 임시로 저장</p>



<p class="wp-block-paragraph">어떤 수열에도 붙을 수 없으면 독립된 시퀀스 시작</p>



<p class="wp-block-paragraph">나중에 불필요한 시퀀스(같은 길이인데 꼬리가 큰 것)는 제거</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>
#include &lt;vector>

using namespace std;

int n; // 수열의 개수
vector&lt;vector&lt;int>> Sequences;

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

    cin >> n;
    if (n &lt;= 0) return 0;

    int num;
    cin >> num;

    // 첫 번째 수로 초기 시퀀스 하나 생성
    vector&lt;int> sequence;
    sequence.push_back(num);
    Sequences.push_back(sequence);

    for (int i = 1; i &lt; n; i++)
    {
        cin >> num;
        int length = Sequences.size();

        bool canExtend = false;
        vector&lt;vector&lt;int>> newSequences;

        // 기존 시퀀스들을 모두 검사
        for (int j = 0; j &lt; length; j++)
        {
            int last = Sequences[j].back();

            // 확장 가능한 경우 : 새로운 시퀀스 생성
            if (last &lt; num)
            {
                canExtend = true;
                vector&lt;int> extendedSeq = Sequences[j];
                extendedSeq.push_back(num);
                newSequences.push_back(extendedSeq);
            }
        }

        // 어떤 시퀀스에도 붙지 못하면 새로운 시퀀스 시작
        if (!canExtend)
        {
            vector&lt;int> newSeq;
            newSeq.push_back(num);
            newSequences.push_back(newSeq);
        }

        // 새로 생긴 시퀀스들을 기존에 합침
        for (auto&amp; seq : newSequences)
            Sequences.push_back(seq);

        // 최적 시퀀스 길이 및 꼬리값 계산
        int maxSeqSize = 0;
        int bestIndex = 0;
        int bestTail = 1000000001;

        for (int j = 0; j &lt; (int)Sequences.size(); j++)
        {
            int sz = Sequences[j].size();
            int tail = Sequences[j].back();
            if (sz > maxSeqSize || (sz == maxSeqSize &amp;&amp; tail &lt; bestTail))
            {
                maxSeqSize = sz;
                bestTail = tail;
                bestIndex = j;
            }
        }

        // 가지치기: 같은 길이인데 꼬리값이 큰 시퀀스 제거
        for (int j = 0; j &lt; (int)Sequences.size();)
        {
            int sz = Sequences[j].size();
            int tail = Sequences[j].back();

            if (sz == maxSeqSize &amp;&amp; tail > bestTail)
            {
                Sequences.erase(Sequences.begin() + j);
            }
            else
            {
                j++;
            }
        }
    }

	// 결과 중 가장 긴 시퀀스 찾기
    int maxSize = 0;
    int bestIdx = 0;
    for (int i = 0; i &lt; (int)Sequences.size(); i++)
    {
        if (Sequences[i].size() > maxSize)
        {
            maxSize = Sequences[i].size();
            bestIdx = i;
        }
    }

    cout &lt;&lt; maxSize &lt;&lt; "\n";
    for (int x : Sequences[bestIdx])
        cout &lt;&lt; x &lt;&lt; " ";

    return 0;
}
</pre>



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



<p class="wp-block-paragraph">브루트포스 방식으로 모든 가능한 증가 수열을 시도하는 방법은 시간 초과 및 메모리 초과로 인하여 통과할 수 없음.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="604" height="509" src="https://lycos7560.com/wp-content/uploads/2025/10/image-3.png" alt="" class="wp-image-40318" srcset="https://lycos7560.com/wp-content/uploads/2025/10/image-3.png 604w, https://lycos7560.com/wp-content/uploads/2025/10/image-3-300x253.png 300w" sizes="(max-width: 604px) 100vw, 604px" /></figure>



<p class="wp-block-paragraph"><strong>매 반복마다</strong> <code>Sequences</code>의 크기가 <strong>기하급수적으로 늘어나는 구조</strong></p>



<p class="wp-block-paragraph">n개의 원소가 들어오면 2ⁿ에 비례하는 시퀀스로 통과하기 힘들다. (O(2ⁿ))</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>단계</th><th>가능한 Sequences 수</th></tr></thead><tbody><tr><td>1</td><td>[ [1] ]</td></tr><tr><td>2</td><td>[ [1], [2], [1,2] ]</td></tr><tr><td>3</td><td>[ [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3] ]</td></tr><tr><td>4</td><td>거의 모든 가능한 증가 부분 수열이 등장함 (약 15개)</td></tr></tbody></table></figure>



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



<h3 class="wp-block-heading">2차 시도 &#8211; <strong>이분 탐색 + 인덱스 추적</strong>을 이용한 LIS 복원 / O(N log N)</h3>



<figure class="wp-block-image size-full"><img decoding="async" width="1042" height="39" src="https://lycos7560.com/wp-content/uploads/2025/10/image-7.png" alt="" class="wp-image-40322" srcset="https://lycos7560.com/wp-content/uploads/2025/10/image-7.png 1042w, https://lycos7560.com/wp-content/uploads/2025/10/image-7-300x11.png 300w, https://lycos7560.com/wp-content/uploads/2025/10/image-7-768x29.png 768w" sizes="(max-width: 1042px) 100vw, 1042px" /></figure>



<p class="wp-block-paragraph">최장 증가 수열 (LIS, Longest Increasing Subsequence)</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>
#include &lt;vector>
#include &lt;algorithm>

using namespace std;

// (LIS, Longest Increasing Subsequence)

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

    int N;
    std::cin >> N;

    vector&lt;int> input(N);
    for (int i = 0; i &lt; N; i++)
        std::cin >> input[i];

    vector&lt;int> tail;  // LIS를 구성하는 인덱스들
    vector&lt;int> prev_idx(N, -1);  //각 요소가 LIS에 포함될 때, 그 직전 요소의 인덱스를 저장


    for (int i = 0; i &lt; N; i++)
    {
        // 이분 탐색으로 input[i]가 tail 배열에서 들어가야 할 위치 찾기
        int lo = 0;
        int hi = (int)tail.size() - 1;
        int pos = (int)tail.size(); // 기본값은 맨 뒤

        while (lo &lt;= hi)
        {
            int mid = (lo + hi) / 2;
            // input[i]보다 크거나 같은 첫 번째 tail 원소 위치(pos)를 찾
            if (input[tail[mid]] &lt; input[i])
            {
                lo = mid + 1;
            }
            else
            {
                pos = mid;
                hi = mid - 1;
            }
        }

        // 이전 인덱스 설정
        if (pos > 0)
        {
            prev_idx[i] = tail[pos - 1];
        }
        else
        {
            prev_idx[i] = -1;  // 첫 번째 요소
        }

        // tail 업데이트
        if (pos == (int)tail.size())
        {
            tail.push_back(i);
        }
        else
        {
            tail[pos] = i;
        }
    }

    // 결과: LIS 길이
    int lis_len = (int)tail.size();
    std::cout &lt;&lt; lis_len &lt;&lt; "\n";

    // 실제 LIS 수열 재구성
    vector&lt;int> lis;
    for (int idx = tail.back(); idx != -1; idx = prev_idx[idx])
    {
        lis.push_back(input[idx]);
    }
    reverse(lis.begin(), lis.end());

    for (int v : lis)
        std::cout &lt;&lt; v &lt;&lt; " ";
    std::cout &lt;&lt; "\n";

    return 0;
}</pre>



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



<figure class="wp-block-image size-full"><img decoding="async" width="651" height="324" src="https://lycos7560.com/wp-content/uploads/2025/10/image-5.png" alt="" class="wp-image-40319" srcset="https://lycos7560.com/wp-content/uploads/2025/10/image-5.png 651w, https://lycos7560.com/wp-content/uploads/2025/10/image-5-300x149.png 300w" sizes="(max-width: 651px) 100vw, 651px" /></figure>



<p class="wp-block-paragraph"><code>input[i]</code>가 들어가야 할 위치(<code>pos</code>)를 찾음</p>



<p class="wp-block-paragraph">즉, <code>tail</code> 배열 내에서 <strong>input[i]보다 작지만 가장 큰 값 다음 위치</strong>를 찾는다.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="513" height="466" src="https://lycos7560.com/wp-content/uploads/2025/10/image-6.png" alt="" class="wp-image-40320" srcset="https://lycos7560.com/wp-content/uploads/2025/10/image-6.png 513w, https://lycos7560.com/wp-content/uploads/2025/10/image-6-300x273.png 300w" sizes="(max-width: 513px) 100vw, 513px" /></figure>



<p class="wp-block-paragraph"><code>prev_idx[i]</code>는 <code>input[i]</code> 바로 앞에 올 LIS 원소의 인덱스입니다.</p>



<p class="wp-block-paragraph"><code>pos > 0</code>이면 → 현재 원소가 &#8220;길이 pos+1&#8243;짜리 LIS의 마지막이 되므로 &#8220;그 바로 이전 원소&#8221;는 <code>tail[pos - 1]</code></p>



<p class="wp-block-paragraph"><code>pos == 0</code>이면 → 수열의 첫 번째 원소이므로 이전이 없음</p>



<p class="wp-block-paragraph"><code>pos == tail.size()</code> → <code>input[i]</code>가 지금 까지의 모든 수보다 크므로 LIS 길이 1 증가</p>



<p class="wp-block-paragraph">그렇지 않으면 → 기존 LIS 후보 중 &#8220;끝값이 더 큰 것&#8221;을 <code>input[i]</code>로 <strong>치환</strong> (더 작은 끝값 유지)</p>



<h4 class="wp-block-heading">예시 1</h4>



<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="">input = [5, 2, 8, 6, 3, 6, 9, 7]</pre>



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



<figure class="wp-block-table"><table><thead><tr><th class="has-text-align-left" data-align="left">단계</th><th class="has-text-align-left" data-align="left">i</th><th class="has-text-align-left" data-align="left">input[i]</th><th class="has-text-align-left" data-align="left">tail (인덱스)</th><th class="has-text-align-left" data-align="left">tail (값으로 표현)</th><th class="has-text-align-left" data-align="left">prev_idx</th><th class="has-text-align-left" data-align="left">설명</th></tr></thead><tbody><tr><td class="has-text-align-left" data-align="left">0</td><td class="has-text-align-left" data-align="left">0</td><td class="has-text-align-left" data-align="left">5</td><td class="has-text-align-left" data-align="left">[0]</td><td class="has-text-align-left" data-align="left">[5]</td><td class="has-text-align-left" data-align="left">[-1, ?, ?, ?, ?, ?, ?, ?]</td><td class="has-text-align-left" data-align="left">첫 번째 원소 → 새로운 LIS 시작</td></tr><tr><td class="has-text-align-left" data-align="left">1</td><td class="has-text-align-left" data-align="left">1</td><td class="has-text-align-left" data-align="left">2</td><td class="has-text-align-left" data-align="left">[1]</td><td class="has-text-align-left" data-align="left">[2]</td><td class="has-text-align-left" data-align="left">[-1, -1, ?, ?, ?, ?, ?, ?]</td><td class="has-text-align-left" data-align="left">2 &lt; 5 → 기존 tail[0] 교체 (더 작은 끝값 유지)</td></tr><tr><td class="has-text-align-left" data-align="left">2</td><td class="has-text-align-left" data-align="left">2</td><td class="has-text-align-left" data-align="left">8</td><td class="has-text-align-left" data-align="left">[1, 2]</td><td class="has-text-align-left" data-align="left">[2, 8]</td><td class="has-text-align-left" data-align="left">[-1, -1, 1, ?, ?, ?, ?, ?]</td><td class="has-text-align-left" data-align="left">8 &gt; 2 → 길이 2짜리 LIS 형성</td></tr><tr><td class="has-text-align-left" data-align="left">3</td><td class="has-text-align-left" data-align="left">3</td><td class="has-text-align-left" data-align="left">6</td><td class="has-text-align-left" data-align="left">[1, 3]</td><td class="has-text-align-left" data-align="left">[2, 6]</td><td class="has-text-align-left" data-align="left">[-1, -1, 1, 1, ?, ?, ?, ?]</td><td class="has-text-align-left" data-align="left">6은 2보다 크지만 8보다 작음 → 8을 6으로 교체</td></tr><tr><td class="has-text-align-left" data-align="left">4</td><td class="has-text-align-left" data-align="left">4</td><td class="has-text-align-left" data-align="left">3</td><td class="has-text-align-left" data-align="left">[1, 4]</td><td class="has-text-align-left" data-align="left">[2, 3]</td><td class="has-text-align-left" data-align="left">[-1, -1, 1, 1, 1, ?, ?, ?]</td><td class="has-text-align-left" data-align="left">3은 2보다 크고 6보다 작음 → 6을 3으로 교체</td></tr><tr><td class="has-text-align-left" data-align="left">5</td><td class="has-text-align-left" data-align="left">5</td><td class="has-text-align-left" data-align="left">6</td><td class="has-text-align-left" data-align="left">[1, 4, 5]</td><td class="has-text-align-left" data-align="left">[2, 3, 6]</td><td class="has-text-align-left" data-align="left">[-1, -1, 1, 1, 1, 4, ?, ?]</td><td class="has-text-align-left" data-align="left">6은 3보다 크므로 길이 3짜리 LIS 생성</td></tr><tr><td class="has-text-align-left" data-align="left">6</td><td class="has-text-align-left" data-align="left">6</td><td class="has-text-align-left" data-align="left">9</td><td class="has-text-align-left" data-align="left">[1, 4, 5, 6]</td><td class="has-text-align-left" data-align="left">[2, 3, 6, 9]</td><td class="has-text-align-left" data-align="left">[-1, -1, 1, 1, 1, 4, 5, ?]</td><td class="has-text-align-left" data-align="left">9 &gt; 6 → 길이 4짜리 LIS 생성</td></tr><tr><td class="has-text-align-left" data-align="left">7</td><td class="has-text-align-left" data-align="left">7</td><td class="has-text-align-left" data-align="left">7</td><td class="has-text-align-left" data-align="left">[1, 4, 5, 7]</td><td class="has-text-align-left" data-align="left">[2, 3, 6, 7]</td><td class="has-text-align-left" data-align="left">[-1, -1, 1, 1, 1, 4, 5, 5]</td><td class="has-text-align-left" data-align="left">7은 6보다 크지만 9보다 작음 → 9를 7로 교체</td></tr></tbody></table></figure>



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



<h4 class="wp-block-heading">예시 2</h4>



<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="">이분 탐색을 이용한 LIS 구성 로직

input = [3, 5, 2, 7, 4, 1, 8]

--------------------------------

i=0 (값: 3)
tail: [] (빈 배열)
이분탐색: tail.size() = 0 → while문 스킵
pos = 0 (기본값)

prev_idx[0] = -1 (pos=0이므로)
tail 업데이트: pos == tail.size() → push_back(0)
결과: tail = [0] (값: [3])

--------------------------------

i=1 (값: 5)
tail: [0] (값: [3])
이분탐색:
  lo=0, hi=0, mid=0
  input[tail[0]] = 3 &lt; 5 → lo = mid+1 = 1
  lo=1 > hi=0 → 종료
pos = tail.size() = 1

prev_idx[1] = tail[0] = 0 (5 앞에 3)
tail 업데이트: push_back(1)
결과: tail = [0,1] (값: [3,5])

--------------------------------

i=2 (값: 2)
tail: [0,1] (값: [3,5])
이분탐색:
  lo=0, hi=1, mid=0
  input[tail[0]] = 3 >= 2 → pos=0, hi=-1
  lo=0 > hi=-1 → 종료
pos = 0

prev_idx[2] = -1 (pos=0이므로)
tail 업데이트: tail[0] = 2
결과: tail = [2,1] (값: [2,5])

--------------------------------

i=3 (값: 7)
tail: [2,1] (값: [2,5])
이분탐색:
  lo=0, hi=1, mid=0: input[tail[0]]=2 &lt; 7 → lo=1
  lo=1, hi=1, mid=1: input[tail[1]]=5 &lt; 7 → lo=2
  lo=2 > hi=1 → 종료
pos = tail.size() = 2

prev_idx[3] = tail[1] = 1 (7 앞에 5)
tail 업데이트: push_back(3)
결과: tail = [2,1,3] (값: [2,5,7])

--------------------------------

i=4 (값: 4)
tail: [2,1,3] (값: [2,5,7])
이분탐색:
  lo=0, hi=2, mid=1: input[tail[1]]=5 >= 4 → pos=1, hi=0
  lo=0, hi=0, mid=0: input[tail[0]]=2 &lt; 4 → lo=1
  lo=1 > hi=0 → 종료
pos = 1

prev_idx[4] = tail[0] = 2 (4 앞에 2)
tail 업데이트: tail[1] = 4
결과: tail = [2,4,3] (값: [2,4,7])

--------------------------------

i=5 (값: 1)
tail: [2,4,3] (값: [2,4,7])
이분탐색:
  lo=0, hi=2, mid=1: input[tail[1]]=4 >= 1 → pos=1, hi=0
  lo=0, hi=0, mid=0: input[tail[0]]=2 >= 1 → pos=0, hi=-1
  lo=0 > hi=-1 → 종료
pos = 0

prev_idx[5] = -1
tail 업데이트: tail[0] = 5
결과: tail = [5,4,3] (값: [1,4,7])

--------------------------------

i=6 (값: 8)

tail: [5,4,3] (값: [1,4,7])
이분탐색:
  lo=0, hi=2, mid=1: input[tail[1]]=4 &lt; 8 → lo=2
  lo=2, hi=2, mid=2: input[tail[2]]=7 &lt; 8 → lo=3
  lo=3 > hi=2 → 종료
pos = tail.size() = 3

prev_idx[6] = tail[2] = 3 (8 앞에 7)
tail 업데이트: push_back(6)
결과: tail = [5,4,3,6] (값: [1,4,7,8])

</pre>



<p class="wp-block-paragraph"></p>
<p>The post <a href="https://lycos7560.com/cpp/%eb%b0%b1%ec%a4%80-14003%eb%b2%88-%ea%b0%80%ec%9e%a5-%ea%b8%b4-%ec%a6%9d%ea%b0%80%ed%95%98%eb%8a%94-%eb%b6%80%eb%b6%84-%ec%88%98%ec%97%b4-5-c/40314/">백준 14003번 (가장 긴 증가하는 부분 수열 5, 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-14003%eb%b2%88-%ea%b0%80%ec%9e%a5-%ea%b8%b4-%ec%a6%9d%ea%b0%80%ed%95%98%eb%8a%94-%eb%b6%80%eb%b6%84-%ec%88%98%ec%97%b4-5-c/40314/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>백준 7569번 (토마토, C++, BFS) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-7569%eb%b2%88-%ed%86%a0%eb%a7%88%ed%86%a0-c-bfs-baekjoon/5667/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-7569%eb%b2%88-%ed%86%a0%eb%a7%88%ed%86%a0-c-bfs-baekjoon/5667/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Fri, 27 Jan 2023 12:18:40 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[3차원]]></category>
		<category><![CDATA[7569]]></category>
		<category><![CDATA[7569번]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cin]]></category>
		<category><![CDATA[cin.tie(NULL)]]></category>
		<category><![CDATA[cout]]></category>
		<category><![CDATA[cout.tie(NULL)]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[ios_base::sync_with_stdio(false)]]></category>
		<category><![CDATA[ios_base::sync_with_stdio(false);]]></category>
		<category><![CDATA[Queue]]></category>
		<category><![CDATA[study]]></category>
		<category><![CDATA[tuple]]></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[백준 7569]]></category>
		<category><![CDATA[백준 7569번]]></category>
		<category><![CDATA[알고리즘]]></category>
		<category><![CDATA[코딩테스트]]></category>
		<category><![CDATA[코테]]></category>
		<category><![CDATA[토마토]]></category>
		<category><![CDATA[튜플]]></category>
		<guid isPermaLink="false">https://lycos7560.com/?p=5667</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 7569번 '토마토' 문제에 대한 글입니다. 'BFS Search' 을 사용하여 해결하였습니다. (This is an article about the 'Tomato' problem in BAEKJOON 7569. Resolved using 'BFS Search'.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-7569%eb%b2%88-%ed%86%a0%eb%a7%88%ed%86%a0-c-bfs-baekjoon/5667/">백준 7569번 (토마토, C++, BFS) [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>



<h1 class="wp-block-heading">토마토</h1>



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



<div style="height:40px" 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">1 초</td><td class="has-text-align-left" data-align="left">256 MB</td><td class="has-text-align-left" data-align="left">63015</td><td class="has-text-align-left" data-align="left">25996</td><td class="has-text-align-left" data-align="left">19053</td><td class="has-text-align-left" data-align="left">41.355%</td></tr></tbody></table></figure>



<div style="height:40px" 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>



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



<figure class="wp-block-image size-full"><img decoding="async" width="506" height="483" src="https://lycos7560.com/wp-content/uploads/2023/01/image-27.png" alt="" class="wp-image-5668" srcset="https://lycos7560.com/wp-content/uploads/2023/01/image-27.png 506w, https://lycos7560.com/wp-content/uploads/2023/01/image-27-300x286.png 300w" sizes="(max-width: 506px) 100vw, 506px" /></figure>



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



<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>



<p class="has-medium-font-size wp-block-paragraph">며칠이 지나면 토마토들이 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라. </p>



<p class="has-medium-font-size wp-block-paragraph">단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다.</p>



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



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



<p class="has-medium-font-size wp-block-paragraph">첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100, 1 ≤ H ≤ 100 이다. </p>



<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">각 줄에는 상자 가로줄에 들어있는 토마토들의 상태가 M개의 정수로 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">정수 1은 익은 토마토, 정수 0 은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다. </p>



<p class="has-medium-font-size wp-block-paragraph">이러한 N개의 줄이 H번 반복하여 주어진다.</p>



<p class="has-medium-font-size wp-block-paragraph">토마토가 하나 이상 있는 경우만 입력으로 주어진다.</p>



<div style="height:40px" 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">만약, 저장될 때부터 모든 토마토가 익어있는 상태이면 0을 출력해야 하고, </p>



<p class="has-medium-font-size wp-block-paragraph">토마토가 모두 익지는 못하는 상황이면 -1을 출력해야 한다.</p>



<div style="height:40px" 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="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 3 1
0 -1 0 0 0
-1 -1 0 1 1
0 0 0 1 1</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="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">-1</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="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">5 3 2
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0</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="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">4</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="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">4 3 2
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
-1 -1 -1 -1
1 1 1 -1</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="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0</pre>



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



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



<p class="wp-block-paragraph"><a href="https://www.acmicpc.net/category/2" target="_blank" rel="noreferrer noopener">Olympiad</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/55" target="_blank" rel="noreferrer noopener">한국정보올림피아드</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/57" target="_blank" rel="noreferrer noopener">한국정보올림피아드시․도지역본선</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/214" target="_blank" rel="noreferrer noopener">지역본선 2013</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/detail/912" target="_blank" rel="noreferrer noopener">초등부</a>&nbsp;3번</p>



<ul class="wp-block-list">
<li>데이터를 추가한 사람:&nbsp;<a href="https://www.acmicpc.net/user/david02324" target="_blank" rel="noreferrer noopener">david02324</a>,&nbsp;<a href="https://www.acmicpc.net/user/kki5150" target="_blank" rel="noreferrer noopener">kki5150</a></li>



<li>문제의 오타를 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/mwy3055" target="_blank" rel="noreferrer noopener">mwy3055</a></li>



<li>잘못된 데이터를 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/tncks0121" target="_blank" rel="noreferrer noopener">tncks0121</a></li>
</ul>



<div style="height:40px" 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/7" target="_blank" rel="noreferrer noopener">그래프 이론</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/11" target="_blank" rel="noreferrer noopener">그래프 탐색</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/126" 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--80);margin-bottom:var(--wp--preset--spacing--80)"/>



<figure class="wp-block-embed is-type-wp-embed is-provider-어제와-내일의-나-그-사이의-이야기 wp-block-embed-어제와-내일의-나-그-사이의-이야기"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="9yXd8hKgRs"><a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-7576%eb%b2%88-%ed%86%a0%eb%a7%88%ed%86%a0-c-bfs-baekjoon/5196/">백준 7576번 (토마토, C++, BFS) [BAEKJOON]</a></blockquote><iframe loading="lazy" class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;백준 7576번 (토마토, C++, BFS) [BAEKJOON]&#8221; &#8212; 어제와 내일의 나 그 사이의 이야기" src="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-7576%eb%b2%88-%ed%86%a0%eb%a7%88%ed%86%a0-c-bfs-baekjoon/5196/embed/#?secret=aELhJB14mS#?secret=9yXd8hKgRs" data-secret="9yXd8hKgRs" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



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



<p class="has-medium-font-size wp-block-paragraph">백준 7576번과 차이점은 3차원 배열을 쓴다는 점 빼고는 다같다. </p>



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



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



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



<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>
#include &lt;tuple>

using namespace std;

constexpr int MAX = 100;

// N 세로, M 가로, H 높이
int N, M, H, dx, dy, dz, maxCnt = 0;

// N, M의 범위 
int map[MAX][MAX][MAX];

// BFS 방문처리
bool mapCheck[MAX][MAX][MAX];

// 탐색하는 방향 설정
int dxdydz[6][3] = { 
         {0, 0, 1},
         {0, 0, -1},
         {1, 0, 0},
         {-1, 0, 0},
         {0, 1, 0},
         {0, -1, 0}
};

queue&lt;tuple&lt;int, int, int>> myQueue;

tuple&lt;int, int, int> tempTuple;

bool falseCheck = true;

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

    cin >> M >> N >> H;


    for (int k = 0; k &lt; H; k++) {
        for (int i = 0; i &lt; N; i++) {
            for (int j = 0; j &lt; M; j++) {              
                    cin >> map[i][j][k];    
            }
        }
    }

    for (int  k = 0; k &lt; H; k++) {
        for (int i = 0; i &lt; N; i++) {
            for (int j = 0; j &lt; M; j++) {
                if (map[i][j][k] == 1) { // 익은 토마토를 큐에 넣고 방문처리
                    mapCheck[i][j][k] = true;
                    map[i][j][k] = 0; // map[i][j][k] = 익은 날짜
                    myQueue.push(make_tuple(i, j, k));
                }
            }
        }
    }


    while (!myQueue.empty()) {

        tempTuple = myQueue.front();
        myQueue.pop();
        // 상/하/좌/우를 탐색하기 위한 반복문
        for (int i = 0; i &lt; 6; i++) {
            dx = get&lt;0>(tempTuple) + dxdydz[i][0];
            dy = get&lt;1>(tempTuple) + dxdydz[i][1];
            dz = get&lt;2>(tempTuple) + dxdydz[i][2];


            // 문제의 범위를 벗어나는 경우 => 넘어간다.
            if (dx &lt; 0 || dy &lt; 0 || dz &lt; 0 || dx >= N || dy >= M || dz >= H) continue;
            // '-1' 인 경우, 이미 방문한 곳 일 경우 => 넘어간다.
            if (mapCheck[dx][dy][dz] == true || map[dx][dy][dz] == -1) continue;

            map[dx][dy][dz] = map[get&lt;0>(tempTuple)][get&lt;1>(tempTuple)][get&lt;2>(tempTuple)] + 1; // 카운트를 올려준다.
            mapCheck[dx][dy][dz] = true; // 방문처리
            myQueue.push(make_tuple(dx, dy, dz));
        }
    }

    for (int k = 0; k &lt; H &amp;&amp; falseCheck; k++) {
        for (int i = 0; i &lt; N &amp;&amp; falseCheck; i++) {
            for (int j = 0; j &lt; M &amp;&amp; falseCheck; j++) {
                    maxCnt = max(maxCnt, map[i][j][k]); // 날짜 출력
                    // 익지 않은 토마토가 방문처리가 안되어있다면 막혀있다는 뜻 
                    if (map[i][j][k] == 0 &amp;&amp; mapCheck[i][j][k] == false)  falseCheck = false;
            }
        }
    }

    // 익지 않은 토마토가 있다면 -1 출력
    // 없다면 날짜 출력
    if (falseCheck) cout &lt;&lt; maxCnt;
    else cout &lt;&lt; -1;

    return 0;
}</pre>



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



<figure class="wp-block-image size-full"><img decoding="async" width="1032" height="99" src="https://lycos7560.com/wp-content/uploads/2023/01/image-28.png" alt="" class="wp-image-5670" srcset="https://lycos7560.com/wp-content/uploads/2023/01/image-28.png 1032w, https://lycos7560.com/wp-content/uploads/2023/01/image-28-300x29.png 300w, https://lycos7560.com/wp-content/uploads/2023/01/image-28-768x74.png 768w" sizes="(max-width: 1032px) 100vw, 1032px" /></figure>



<div style="height:40px" 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/%eb%b0%b1%ec%a4%80-7569%eb%b2%88-%ed%86%a0%eb%a7%88%ed%86%a0-c-bfs-baekjoon/5667/">백준 7569번 (토마토, C++, BFS) [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-7569%eb%b2%88-%ed%86%a0%eb%a7%88%ed%86%a0-c-bfs-baekjoon/5667/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>백준 11723번 (집합, C++, 비트마스킹) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11723%eb%b2%88-%ec%a7%91%ed%95%a9-c-%eb%b9%84%ed%8a%b8%eb%a7%88%ec%8a%a4%ed%82%b9-baekjoon/5573/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11723%eb%b2%88-%ec%a7%91%ed%95%a9-c-%eb%b9%84%ed%8a%b8%eb%a7%88%ec%8a%a4%ed%82%b9-baekjoon/5573/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Thu, 26 Jan 2023 10:42:15 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[11723]]></category>
		<category><![CDATA[11723번]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cin.tie(NULL)]]></category>
		<category><![CDATA[cout.tie(NULL)]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[ios_base::sync_with_stdio(false)]]></category>
		<category><![CDATA[ios_base::sync_with_stdio(false);]]></category>
		<category><![CDATA[SET]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[study]]></category>
		<category><![CDATA[공부]]></category>
		<category><![CDATA[구현]]></category>
		<category><![CDATA[기본]]></category>
		<category><![CDATA[기초]]></category>
		<category><![CDATA[배열]]></category>
		<category><![CDATA[백준]]></category>
		<category><![CDATA[백준 11723]]></category>
		<category><![CDATA[백준 11723번]]></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=5573</guid>

					<description><![CDATA[<p>백준(BAEKJOON) 11723번 '집합' 문제에 대한 글 입니다. 비트마스킹, 배열, Set을 이용하여 해결하였습니다. (This is an article about the 'collection' problem in BAEKJOON 11723. It was solved using bit masking, arrangement, and Set.)</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11723%eb%b2%88-%ec%a7%91%ed%95%a9-c-%eb%b9%84%ed%8a%b8%eb%a7%88%ec%8a%a4%ed%82%b9-baekjoon/5573/">백준 11723번 (집합, 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>



<h1 class="wp-block-heading">집합</h1>



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



<div style="height:40px" 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">1.5 초</td><td class="has-text-align-left" data-align="left">4 MB</td><td class="has-text-align-left" data-align="left">69837</td><td class="has-text-align-left" data-align="left">21400</td><td class="has-text-align-left" data-align="left">15369</td><td class="has-text-align-left" data-align="left">29.201%</td></tr></tbody></table></figure>



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



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



<p class="has-medium-font-size wp-block-paragraph">비어있는 공집합 S가 주어졌을 때, 아래 연산을 수행하는 프로그램을 작성하시오.</p>



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



<p class="has-medium-font-size wp-block-paragraph"><code>add x</code>: S에 x를 추가한다. (1&nbsp;≤ x ≤ 20) S에 x가 이미 있는 경우에는 연산을 무시한다.</p>



<p class="has-medium-font-size wp-block-paragraph"><code>remove&nbsp;x</code>: S에서 x를 제거한다. (1&nbsp;≤ x ≤ 20)&nbsp;S에 x가 없는 경우에는 연산을 무시한다.</p>



<p class="has-medium-font-size wp-block-paragraph"><code>check x</code>: S에 x가 있으면 1을, 없으면 0을 출력한다.&nbsp;(1 ≤ x ≤ 20)</p>



<p class="has-medium-font-size wp-block-paragraph"><code>toggle x</code>: S에 x가 있으면 x를 제거하고, 없으면 x를 추가한다. (1&nbsp;≤ x ≤ 20)</p>



<p class="has-medium-font-size wp-block-paragraph"><code>all</code>: S를 {1, 2, &#8230;, 20} 으로 바꾼다.</p>



<p class="has-medium-font-size wp-block-paragraph"><code>empty</code>: S를 공집합으로 바꾼다.&nbsp;</p>



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



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



<p class="has-medium-font-size wp-block-paragraph">첫째 줄에 수행해야 하는 연산의 수 M (1 ≤ M ≤ 3,000,000)이 주어진다.</p>



<p class="has-medium-font-size wp-block-paragraph">둘째 줄부터 M개의 줄에 수행해야 하는 연산이 한 줄에 하나씩 주어진다.</p>



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



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



<p class="has-medium-font-size wp-block-paragraph"><code>check</code>&nbsp;연산이 주어질때마다, 결과를 출력한다.</p>



<div style="height:40px" 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="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">26
add 1
add 2
check 1
check 2
check 3
remove 2
check 1
check 2
toggle 3
check 1
check 2
check 3
check 4
all
check 10
check 20
toggle 10
remove 20
check 10
check 20
empty
check 1
toggle 1
check 1
toggle 1
check 1</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="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1
1
0
1
0
1
0
1
0
1
1
0
0
0
1
0</pre>



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



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



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



<li>빠진 조건을 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/djm03178" target="_blank" rel="noreferrer noopener">djm03178</a></li>



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



<li>문제의 오타를 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/pichulia" target="_blank" rel="noreferrer noopener">pichulia</a></li>
</ul>



<div style="height:40px" 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/102" target="_blank" rel="noreferrer noopener">구현</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/14" 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--80);margin-bottom:var(--wp--preset--spacing--80)"/>



<p class="has-medium-font-size wp-block-paragraph">3가지 방법으로 해결</p>



<p class="has-medium-font-size wp-block-paragraph">=&gt; 비트 마스킹. 배열, set </p>



<p class="has-medium-font-size wp-block-paragraph"><strong>비트 마스킹</strong>이 가장 빠르다.</p>



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



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



<p class="has-medium-font-size wp-block-paragraph"><strong>1. 자료구조 Set</strong></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;set>

using namespace std;

set&lt;int> mySet;

int N, temp;

string str;

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

	cin >> N;
	while (N-- > 0) {
		cin >> str;
		if (str == "add") {
			// add x: S에 x를 추가한다. (1 ≤ x ≤ 20) 
			// S에 x가 이미 있는 경우에는 연산을 무시한다.
			cin >> temp;
			mySet.insert(temp);
		}
		else if (str == "remove") {
			//remove x : S에서 x를 제거한다. (1 ≤ x ≤ 20) 
			// S에 x가 없는 경우에는 연산을 무시한다.
			cin >> temp;
			mySet.erase(temp);
		}
		else if (str == "check") {
			// check x: S에 x가 있으면 1을, 
			// 없으면 0을 출력한다. (1 ≤ x ≤ 20)
			cin >> temp;
			if (mySet.count(temp)) cout &lt;&lt; "1" &lt;&lt; "\n";
			else cout &lt;&lt; "0" &lt;&lt; "\n";
		}
		else if (str == "toggle") {
			// toggle x : S에 x가 있으면 x를 제거하고, 
			// 없으면 x를 추가한다. (1 ≤ x ≤ 20)
			cin >> temp;
			if (mySet.count(temp)) mySet.erase(temp);
			else mySet.insert(temp);
		}
		else if (str == "all") {
			// all: S를 {1, 2, ..., 20} 으로 바꾼다.
			for (int i = 1; i &lt;= 20; i++) mySet.insert(i);
		}
		else { 
			// empty: S를 공집합으로 바꾼다. 
			mySet.clear();
		}
	}

	return 0;
}</pre>



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



<p class="has-medium-font-size wp-block-paragraph"><strong>2. 배열</strong></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>
using namespace std;

bool arr[20];
int N, temp;

string str;

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

	cin >> N;
	while (N-- > 0) {
		cin >> str;
		if (str == "add") {
			// add x: S에 x를 추가한다. (1 ≤ x ≤ 20) 
			// S에 x가 이미 있는 경우에는 연산을 무시한다.
			cin >> temp;
			arr[temp-1] = 1;
		}
		else if (str == "remove") {
			//remove x : S에서 x를 제거한다. (1 ≤ x ≤ 20) 
			// S에 x가 없는 경우에는 연산을 무시한다.
			cin >> temp;
			arr[temp-1] = 0;
		}
		else if (str == "check") {
			// check x: S에 x가 있으면 1을, 
			// 없으면 0을 출력한다. (1 ≤ x ≤ 20)
			cin >> temp;
			cout &lt;&lt; arr[temp-1] &lt;&lt; "\n";
		}
		else if (str == "toggle") {
			// toggle x : S에 x가 있으면 x를 제거하고, 
			// 없으면 x를 추가한다. (1 ≤ x ≤ 20)
			cin >> temp;
			if (arr[temp-1] == 1) arr[temp-1] = 0;
			else  arr[temp-1] = 1;
		}
		else if (str == "all") {
			// all: S를 {1, 2, ..., 20} 으로 바꾼다.
			for (int i = 0; i &lt; 20; i++) arr[i] = 1;
		}
		else {
			// empty: S를 공집합으로 바꾼다. 
			fill(arr, arr + 20, 0);
		}
	}

	return 0;
}
</pre>



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



<p class="has-medium-font-size wp-block-paragraph"><strong>3. 비트 마스킹</strong></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>

using namespace std;

int S = 0; // 비트마스킹
string str;
int N, temp;

int main() {

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

	cin >> N;
	while(N-- > 0) {

		cin >> str;
		if (str == "add") {
			// add x: S에 x를 추가한다. (1 ≤ x ≤ 20) 
			// S에 x가 이미 있는 경우에는 연산을 무시한다.
			cin >> temp;
			S = S | (1 &lt;&lt; temp);
		}
		else if (str == "remove") {
			//remove x : S에서 x를 제거한다. (1 ≤ x ≤ 20) 
			// S에 x가 없는 경우에는 연산을 무시한다.
			cin >> temp;
			S = S &amp; ~(1 &lt;&lt; temp);
		}
		else if (str == "check") {
			// check x: S에 x가 있으면 1을, 
			// 없으면 0을 출력한다. (1 ≤ x ≤ 20)
			cin >> temp;
			if (S &amp; (1 &lt;&lt; temp)) cout &lt;&lt; "1\n";
			else cout &lt;&lt; "0\n";
		}
		else if (str == "toggle") {
			// toggle x : S에 x가 있으면 x를 제거하고, 
			// 없으면 x를 추가한다. (1 ≤ x ≤ 20)
			cin >> temp;
			if (S &amp; (1 &lt;&lt; temp)) {
				S = S &amp; ~(1 &lt;&lt; temp);
			}
			else {
				S = S | (1 &lt;&lt; temp);
			}
		}
		else if (str == "all") {
			// all: S를 {1, 2, ..., 20} 으로 바꾼다.
			S = (1 &lt;&lt; 21) - 1;
		}
		else {
			// empty: S를 공집합으로 바꾼다. 
			S = 0;
		}
	}

	return 0;
}</pre>



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



<figure class="wp-block-image size-full"><img decoding="async" width="1030" height="221" src="https://lycos7560.com/wp-content/uploads/image-1062.png" alt="" class="wp-image-5582" srcset="https://lycos7560.com/wp-content/uploads/image-1062.png 1030w, https://lycos7560.com/wp-content/uploads/image-1062-300x64.png 300w, https://lycos7560.com/wp-content/uploads/image-1062-768x165.png 768w" sizes="(max-width: 1030px) 100vw, 1030px" /></figure>



<div style="height:40px" 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/%eb%b0%b1%ec%a4%80-11723%eb%b2%88-%ec%a7%91%ed%95%a9-c-%eb%b9%84%ed%8a%b8%eb%a7%88%ec%8a%a4%ed%82%b9-baekjoon/5573/">백준 11723번 (집합, C++, 비트마스킹) [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://lycos7560.com/cpp/baekjoon_online_judge/%eb%b0%b1%ec%a4%80-11723%eb%b2%88-%ec%a7%91%ed%95%a9-c-%eb%b9%84%ed%8a%b8%eb%a7%88%ec%8a%a4%ed%82%b9-baekjoon/5573/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>백준 6987번 (월드컵, C++,DFS ) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon_online_judge/baekjoon-6987%eb%b2%88-%ec%9b%94%eb%93%9c%ec%bb%b5-cdfs/2992/</link>
					<comments>https://lycos7560.com/cpp/baekjoon_online_judge/baekjoon-6987%eb%b2%88-%ec%9b%94%eb%93%9c%ec%bb%b5-cdfs/2992/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Fri, 02 Dec 2022 23:38:45 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[6987]]></category>
		<category><![CDATA[6987번]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[dfs]]></category>
		<category><![CDATA[worldcup]]></category>
		<category><![CDATA[배열]]></category>
		<category><![CDATA[백준]]></category>
		<category><![CDATA[백준 6987]]></category>
		<category><![CDATA[백준 6987번]]></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=2992</guid>

					<description><![CDATA[<p>백준 6987번 문제를 풀이한 글입니다.<br />
DFS를 이용하여 풀이하였습니다.</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/baekjoon-6987%eb%b2%88-%ec%9b%94%eb%93%9c%ec%bb%b5-cdfs/2992/">백준 6987번 (월드컵, C++,DFS ) [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:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="wp-block-heading">월드컵</h1>



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



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



<figure id="problem-info" class="wp-block-table"><table><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">1 초</td><td class="has-text-align-left" data-align="left">128 MB</td><td class="has-text-align-left" data-align="left">8325</td><td class="has-text-align-left" data-align="left">2402</td><td class="has-text-align-left" data-align="left">1702</td><td class="has-text-align-left" data-align="left">31.379%</td></tr></tbody></table></figure>



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



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



<p class="has-medium-font-size wp-block-paragraph">월드컵 조별 최종 예선에서는 6개국으로 구성된 각 조별로 동일한 조에 소속된 국가들과 한 번씩, 각 국가별로 총 5번의 경기를 치른다. </p>



<p class="has-medium-font-size wp-block-paragraph">조별 리그가 끝난 후, 기자가 보내온 각 나라의 승, 무승부, 패의 수가 가능한 결과인지를 판별하려고 한다. </p>



<p class="has-medium-font-size wp-block-paragraph">다음은 가능한 결과와 가능하지 않은 결과의 예이다.</p>



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



<figure class="wp-block-image size-full"><img decoding="async" width="1155" height="373" src="https://lycos7560.com/wp-content/uploads/image-481.png" alt="" class="wp-image-2993" srcset="https://lycos7560.com/wp-content/uploads/image-481.png 1155w, https://lycos7560.com/wp-content/uploads/image-481-300x97.png 300w, https://lycos7560.com/wp-content/uploads/image-481-768x248.png 768w" sizes="(max-width: 1155px) 100vw, 1155px" /></figure>



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



<p class="has-medium-font-size wp-block-paragraph">네 가지의 결과가 주어질 때 각각의 결과에 대하여 가능하면 1, 불가능하면 0을 출력하는 프로그램을 작성하시오.</p>



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



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



<p class="has-medium-font-size wp-block-paragraph">첫째 줄부터 넷째 줄까지 각 줄마다 6개국의 결과가 나라별로 승, 무승부, 패의 순서로 빈칸을 하나 사이에 두고 18개의 숫자로 주어진다. </p>



<p class="has-medium-font-size wp-block-paragraph">승, 무, 패의 수는 6보다 작거나 같은 자연수 또는 0이다.</p>



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



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



<p class="has-medium-font-size wp-block-paragraph">입력에서 주어진 네 가지 결과에 대하여 가능한 결과는 1, 불가능한 결과는 0을 빈칸을 하나 사이에 두고 출력한다.</p>



<div style="height:43px" 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="">5 0 0 3 0 2 2 0 3 0 0 5 4 0 1 1 0 4
4 1 0 3 0 2 4 1 0 1 1 3 0 0 5 1 1 3
5 0 0 4 0 1 2 2 1 2 0 3 1 0 4 0 0 5
5 0 0 3 1 1 2 1 2 2 0 3 0 0 5 1 0 4</pre>



<div style="height:57px" 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="">1 1 0 0</pre>



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



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



<p class="wp-block-paragraph"><a href="https://www.acmicpc.net/category/2" target="_blank" rel="noreferrer noopener">Olympiad</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/55" target="_blank" rel="noreferrer noopener">한국정보올림피아드</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/65" target="_blank" rel="noreferrer noopener">KOI 2008</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/detail/352" target="_blank" rel="noreferrer noopener">초등부</a>&nbsp;2번</p>



<p class="wp-block-paragraph"><a href="https://www.acmicpc.net/category/2" target="_blank" rel="noreferrer noopener">Olympiad</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/55" target="_blank" rel="noreferrer noopener">한국정보올림피아드</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/65" target="_blank" rel="noreferrer noopener">KOI 2008</a>&nbsp;&gt;&nbsp;<a href="https://www.acmicpc.net/category/detail/353" target="_blank" rel="noreferrer noopener">중등부</a>&nbsp;1번</p>



<ul class="wp-block-list">
<li>빠진 조건을 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/djm03178" target="_blank" rel="noreferrer noopener">djm03178</a></li>



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



<div style="height:33px" 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/125" target="_blank" rel="noreferrer noopener">브루트포스 알고리즘</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/5" target="_blank" rel="noreferrer noopener">백트래킹</a></li>
</ul>



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



<p class="has-medium-font-size wp-block-paragraph">처음 문제에 대한 접근을 입력 받은 예제에서 승/무/패에 대한 데이터를 가지고 해결하는 방법으로 생각하여 조건을 추가하면서 해결하려고 했다.</p>



<p class="has-medium-font-size wp-block-paragraph">1시간 정도 해보다&#8230;. 내가 못하는 건지 계속 다른 결과만 나왔다.</p>



<p class="has-medium-font-size wp-block-paragraph">고민하다가 알고리즘 분류에서&nbsp;브루트 포스와&nbsp;백트래킹이&nbsp;보이길래&#8230; 아 하나하나 해서&nbsp;비교해 보는 것이&nbsp;좋겠구나 해서&nbsp;방향을 바꾸었다.</p>



<p class="has-medium-font-size wp-block-paragraph">길을 잘못 들어서 고민을 많이 한 문제</p>



<div style="height:31px" 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>



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



<p class="has-medium-font-size wp-block-paragraph">가능한 경기는 총 15경기 배열로 어느 팀과의 경기인지 표시</p>



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



<figure class="wp-block-image size-full"><img decoding="async" width="409" height="178" src="https://lycos7560.com/wp-content/uploads/image-482.png" alt="" class="wp-image-2997" srcset="https://lycos7560.com/wp-content/uploads/image-482.png 409w, https://lycos7560.com/wp-content/uploads/image-482-300x131.png 300w" sizes="(max-width: 409px) 100vw, 409px" /></figure>



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



<figure class="wp-block-image size-full"><img decoding="async" width="940" height="102" src="https://lycos7560.com/wp-content/uploads/image-485.png" alt="" class="wp-image-3000" srcset="https://lycos7560.com/wp-content/uploads/image-485.png 940w, https://lycos7560.com/wp-content/uploads/image-485-300x33.png 300w, https://lycos7560.com/wp-content/uploads/image-485-768x83.png 768w" sizes="(max-width: 940px) 100vw, 940px" /></figure>



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



<p class="has-medium-font-size wp-block-paragraph">문제를 입력받는 부분도 처음에는 string 값으로 받아서 처리하려고 하다가 </p>



<p class="has-medium-font-size wp-block-paragraph">테스트 케이스는 4가지로 이미 정해져 있고 / 팀은 6팀 / 결과는 승 무 패 -&gt; 4 / 6 / 3 배열로 처리하였다.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="751" height="88" src="https://lycos7560.com/wp-content/uploads/image-484.png" alt="" class="wp-image-2999" srcset="https://lycos7560.com/wp-content/uploads/image-484.png 751w, https://lycos7560.com/wp-content/uploads/image-484-300x35.png 300w" sizes="(max-width: 751px) 100vw, 751px" /></figure>



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



<p class="has-medium-font-size wp-block-paragraph">테스트 케이스와 비교하는 부분은 DFS로 비교하였다.</p>



<p class="has-medium-font-size wp-block-paragraph">game의 수가 15번이면 테스트 케이스와 비교하여 스코어가 다른값 없이 통과하면 결과에 1을 넣어주어 나중에 출력 (기본 0)</p>



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



<figure class="wp-block-image size-full"><img decoding="async" width="743" height="990" src="https://lycos7560.com/wp-content/uploads/image-486.png" alt="" class="wp-image-3001" srcset="https://lycos7560.com/wp-content/uploads/image-486.png 743w, https://lycos7560.com/wp-content/uploads/image-486-225x300.png 225w" sizes="(max-width: 743px) 100vw, 743px" /></figure>



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



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



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



<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 predictedArr[4][6][3];

// 가능한 경기는 총 15경기
int gameArr1[15] = {0,0,0,0,0,1,1,1,1,2,2,2,3,3,4};
int gameArr2[15] = {1,2,3,4,5,2,3,4,5,3,4,5,4,5,5};

// Win Draw Lose 결과
int scoreWDL[6][3];

// 결과를 저장해서 마지막에 출력
int result[4];


void Initalization()
{
	//결과 초기화
	for (int i = 0; i &lt; 4; i++)
	{
		result[i] = 0;
	}

	// 예상 스코어를 받습니다.
	for (int n = 0; n &lt; 4; n++)
	{
		for (int i = 0; i &lt; 6; i++)
		{
			for (int j = 0; j &lt; 3; j++)
			{
				cin >> predictedArr[n][i][j];
			}
		}
	}
}

void CheckScoreRecursive(int gameCnt)
{
	// 만약 모든 경기가 끝났다면
	if (gameCnt == 15) {
		//비교
		for (int n = 0; n &lt; 4; n++) {

			bool check = true;

			for (int i = 0; i &lt; 6; i++) {
				for (int j = 0; j &lt; 3; j++) {
					if (predictedArr[n][i][j] != scoreWDL[i][j]) {
						check = false;
						break;
					}
				}

				// 예측 결과가 가능하면 브레이크
				if (!check) break;
			}

			// 해당 결과가 가능하면 진입
			if (check) {
				result[n] = 1;
			}
		}

		return;
	}

	// 기준은 Arr1
	// 승리했을 경우
	scoreWDL[gameArr1[gameCnt]][0]++;
	scoreWDL[gameArr2[gameCnt]][2]++;
	CheckScoreRecursive(gameCnt + 1);
	scoreWDL[gameArr1[gameCnt]][0]--;
	scoreWDL[gameArr2[gameCnt]][2]--;

	// 무승부일 경우
	scoreWDL[gameArr1[gameCnt]][1]++;
	scoreWDL[gameArr2[gameCnt]][1]++;
	CheckScoreRecursive(gameCnt + 1);
	scoreWDL[gameArr1[gameCnt]][1]--;
	scoreWDL[gameArr2[gameCnt]][1]--;

	// 패배의 경우
	scoreWDL[gameArr1[gameCnt]][2]++;
	scoreWDL[gameArr2[gameCnt]][0]++;
	CheckScoreRecursive(gameCnt + 1);
	scoreWDL[gameArr1[gameCnt]][2]--;
	scoreWDL[gameArr2[gameCnt]][0]--;
}

int main()
{
	Initalization();

	// DFS로 시작 
	CheckScoreRecursive(0);

	// 결과 출력
	for (int i = 0; i &lt; 4; i++)
	{
		cout &lt;&lt; result[i] &lt;&lt; " ";
	}

	return 0;
}</pre>



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



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



<div style="height:100px" 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; text-align:center;"
     data-ad-layout="in-article"
     data-ad-format="fluid"
     data-ad-client="ca-pub-5698326622209671"
     data-ad-slot="5078714126"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon_online_judge/baekjoon-6987%eb%b2%88-%ec%9b%94%eb%93%9c%ec%bb%b5-cdfs/2992/">백준 6987번 (월드컵, C++,DFS ) [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://lycos7560.com/cpp/baekjoon_online_judge/baekjoon-6987%eb%b2%88-%ec%9b%94%eb%93%9c%ec%bb%b5-cdfs/2992/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>백준 1525번 (퍼즐, C++, BFS) [BAEKJOON]</title>
		<link>https://lycos7560.com/cpp/baekjoon-1525%eb%b2%88-%ed%8d%bc%ec%a6%90-c-bfs/450/</link>
					<comments>https://lycos7560.com/cpp/baekjoon-1525%eb%b2%88-%ed%8d%bc%ec%a6%90-c-bfs/450/#respond</comments>
		
		<dc:creator><![CDATA[lycos7560]]></dc:creator>
		<pubDate>Thu, 27 Oct 2022 12:45:47 +0000</pubDate>
				<category><![CDATA[BaekjoonOnlineJudge]]></category>
		<category><![CDATA[C++/CPP]]></category>
		<category><![CDATA[1525]]></category>
		<category><![CDATA[Baekjoon]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[메모리초과]]></category>
		<category><![CDATA[배열]]></category>
		<category><![CDATA[백준]]></category>
		<category><![CDATA[백준 1525]]></category>
		<category><![CDATA[백준 1525번]]></category>
		<category><![CDATA[시간초과]]></category>
		<category><![CDATA[알고리즘]]></category>
		<category><![CDATA[예제]]></category>
		<category><![CDATA[코딩테스트]]></category>
		<category><![CDATA[코테]]></category>
		<category><![CDATA[퍼즐]]></category>
		<guid isPermaLink="false">https://lycos7560.synology.me/?p=450</guid>

					<description><![CDATA[<p>퍼즐 www.acmicpc.net/problem/1525 시간 제한 메모리 제한 제출 정답 맞힌 사람 정답 비율 2 초 128 MB 173282 49633 31180 25.184% 문제 3×3 표에 다음과 같이 수가 채워져 있다. 오른쪽 아래 가장 끝 칸은 비어 있는 칸이다. 어떤 수와 인접해 있는 네 개의 칸 중에 하나가 비어 있으면, 수를 그 칸으로 이동시킬 수가 있다. 물론 표 [&#8230;]</p>
<p>The post <a href="https://lycos7560.com/cpp/baekjoon-1525%eb%b2%88-%ed%8d%bc%ec%a6%90-c-bfs/450/">백준 1525번 (퍼즐, C++, BFS) [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:100px" aria-hidden="true" class="wp-block-spacer"></div>



<h1 class="has-huge-font-size wp-block-heading"><strong>퍼즐</strong></h1>



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



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



<figure id="problem-info" class="wp-block-table is-style-regular"><table class="has-ast-global-color-8-color has-ast-global-color-6-background-color has-text-color has-background 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">128 MB</td><td class="has-text-align-left" data-align="left">173282</td><td class="has-text-align-left" data-align="left">49633</td><td class="has-text-align-left" data-align="left">31180</td><td class="has-text-align-left" data-align="left">25.184%</td></tr></tbody></table></figure>



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



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



<p class="has-medium-font-size wp-block-paragraph">3×3 표에 다음과 같이 수가 채워져 있다. 오른쪽 아래 가장 끝 칸은 비어 있는 칸이다.</p>



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



<figure class="wp-block-image size-full"><img decoding="async" width="558" height="138" src="https://lycos7560.com/wp-content/uploads/image-48.png" alt="" class="wp-image-2227" srcset="https://lycos7560.com/wp-content/uploads/image-48.png 558w, https://lycos7560.com/wp-content/uploads/image-48-300x74.png 300w" sizes="(max-width: 558px) 100vw, 558px" /></figure>



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



<p class="has-medium-font-size wp-block-paragraph">어떤 수와 인접해 있는 네 개의 칸 중에 하나가 비어 있으면, 수를 그 칸으로 이동시킬 수가 있다. <br><br>물론 표 바깥으로 나가는 경우는 불가능하다. <br><br>우리의 목표는 초기 상태가 주어졌을 때, 최소의 이동으로 위와 같은 정리된 상태를 만드는 것이다. <br><br>다음의 예를 보자.<br></p>



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



<figure class="wp-block-image size-full"><img decoding="async" width="801" height="559" src="https://lycos7560.com/wp-content/uploads/image-47.png" alt="" class="wp-image-2226" srcset="https://lycos7560.com/wp-content/uploads/image-47.png 801w, https://lycos7560.com/wp-content/uploads/image-47-300x209.png 300w, https://lycos7560.com/wp-content/uploads/image-47-768x536.png 768w" sizes="(max-width: 801px) 100vw, 801px" /></figure>



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



<p class="has-medium-font-size wp-block-paragraph">가장&nbsp;윗 상태에서 세 번의 이동을 통해 정리된 상태를 만들 수 있다. <br><br>이와 같이 최소 이동 횟수를 구하는 프로그램을 작성하시오.</p>



<h2 class="has-large-font-size wp-block-heading">입력</h2>



<p class="has-medium-font-size wp-block-paragraph">세 줄에 걸쳐서 표에 채워져 있는 아홉 개의 수가 주어진다. <br><br>한 줄에 세 개의 수가 주어지며, 빈 칸은 0으로 나타낸다.</p>



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



<h2 class="has-large-font-size wp-block-heading">출력</h2>



<p class="has-medium-font-size wp-block-paragraph">첫째 줄에 최소의 이동 횟수를 출력한다. <br><br>이동이 불가능한 경우 -1을 출력한다.</p>



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



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



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1 0 3
4 2 5
7 8 6</pre>



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



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



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">3
</pre>



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



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



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">3 6 0
8 1 2
7 4 5
</pre>



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



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



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



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



<h2 class="has-medium-font-size wp-block-heading">출처</h2>



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



<li>잘못된 데이터를 찾은 사람:&nbsp;<a href="https://www.acmicpc.net/user/djm03178" target="_blank" rel="noreferrer noopener">djm03178</a></li>



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



<li>메모리 제한을 수정한 사람:&nbsp;<a href="https://www.acmicpc.net/user/portableangel" target="_blank" rel="noreferrer noopener">portableangel</a></li>
</ul>



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



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



<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/7" target="_blank" rel="noreferrer noopener">그래프 이론</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/11" target="_blank" rel="noreferrer noopener">그래프 탐색</a></li>



<li><a href="https://www.acmicpc.net/problem/tag/126" target="_blank" rel="noreferrer noopener">너비 우선 탐색</a></li>
</ul>



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



<h2 class="has-medium-font-size wp-block-heading">메모리 제한</h2>



<ul class="wp-block-list">
<li>Java 8: 256 MB</li>



<li>Java 8 (OpenJDK): 256 MB</li>



<li>Java 11: 256 MB</li>



<li>Kotlin (JVM): 256 MB</li>
</ul>



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



<hr class="wp-block-separator has-text-color has-ast-global-color-8-color has-css-opacity has-ast-global-color-8-background-color has-background 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">시간 초과 및 메모리 초과로 고통 받은 문제<br><br>메모리의 제한으로 배열보다 string 값으로 퍼즐을 표현한 것이 이 문제의 포인트 같다. </p>



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



<figure class="wp-block-image size-full"><img decoding="async" width="396" height="250" src="https://lycos7560.com/wp-content/uploads/2022/11/image-12.png" alt="" class="wp-image-1989" srcset="https://lycos7560.com/wp-content/uploads/2022/11/image-12.png 396w, https://lycos7560.com/wp-content/uploads/2022/11/image-12-300x189.png 300w" sizes="(max-width: 396px) 100vw, 396px" /></figure>



<div style="height:101px" 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>



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



<h2 class="has-huge-font-size wp-block-heading"><strong> 통과된 코드 (BFS) </strong></h2>



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



<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;queue>
#include&lt;string>
#include&lt;algorithm>
#include&lt;set>

using namespace std;

string puzzle; // 퍼즐의 상태를 저장할 변수

queue&lt;pair&lt;string, int>> myqueue;
// 퍼즐의 초기상태와 실행 횟수를 넣어줌
// 탐색 시 상 / 하 / 좌 / 우 움직임 정의

set&lt;string> checkset;
// 상태가 중복되는 것을 허용하지 않게 만듬(최단거리를 계산해준다.)
// 같은 값을 넣어도 하나만 존재

int dx[4] = { 0, 0, 1, -1 };
int dy[4] = { 1, -1, 0, 0 };

int result = -1;

void BfsAndCheck()
{
	myqueue.push({puzzle, 0});
	checkset.insert(puzzle);
	
	while (!myqueue.empty())
	{

		string currentString = myqueue.front().first;
		int countTry = myqueue.front().second;
		myqueue.pop();



		if (currentString == "123456780" &amp;&amp;(result == -1 || result > countTry))
		{
			result = countTry;
		}

		int zeroPos = currentString.find('0'); //  0의 위치찾고 반복자를 찾음

		// 인덱스 값으로 행과 열의 값을 가져온다.
		int x = zeroPos / 3;
		int y = zeroPos % 3;


		// 해당 위치에서 상 하 좌 우 4가지 방향으로 자리를 바꾸면서 큐에 넣어준다. 
		for (int i = 0; i &lt; 4; i++)
		{
			int nx = x + dx[i];
			int ny = y + dy[i];

			// 범위를 넘어가면 넘김
			if (nx &lt; 0 || nx >= 3 || ny &lt; 0 || ny >= 3)
			{
				continue;
			}

			string next = currentString;
			//   현위치, 다음 위치를 바꿈
			swap(next[x * 3 + y], next[nx * 3 + ny]);

			// 방문한 경험이 있는지 확인
			if (checkset.count(next) == 0)
			{
				checkset.insert(next);
				myqueue.push({ next, countTry + 1 });
			}
		}
	}
}

// 값을 입력받아 퍼즐을 셋팅
void Init()
{
	char temp;
	for (int i = 0; i &lt; 9; i++)
	{
		cin >> temp;
		puzzle.push_back(temp); // 문자열의 맨 끝에 추가
	}
}

int main()
{
	Init();
	BfsAndCheck();
	//cout &lt;&lt; ANSWER &lt;&lt; "\n" &lt;&lt; puzzle;
	cout &lt;&lt; result;
	return 0;
}</pre>



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



<figure class="wp-block-image size-full"><img decoding="async" width="825" height="506" src="https://lycos7560.com/wp-content/uploads/image-46.png" alt="" class="wp-image-2224" srcset="https://lycos7560.com/wp-content/uploads/image-46.png 825w, https://lycos7560.com/wp-content/uploads/image-46-300x184.png 300w, https://lycos7560.com/wp-content/uploads/image-46-768x471.png 768w" sizes="(max-width: 825px) 100vw, 825px" /></figure>



<div style="height:100px" 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; text-align:center;"
     data-ad-layout="in-article"
     data-ad-format="fluid"
     data-ad-client="ca-pub-5698326622209671"
     data-ad-slot="5078714126"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

<p>The post <a href="https://lycos7560.com/cpp/baekjoon-1525%eb%b2%88-%ed%8d%bc%ec%a6%90-c-bfs/450/">백준 1525번 (퍼즐, C++, BFS) [BAEKJOON]</a> appeared first on <a href="https://lycos7560.com">어제와 내일의 나 그 사이의 이야기</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://lycos7560.com/cpp/baekjoon-1525%eb%b2%88-%ed%8d%bc%ec%a6%90-c-bfs/450/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
