<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>i_am_gr00t.log</title>
        <link>https://velog.io/</link>
        <description>붉은다리 제프</description>
        <lastBuildDate>Wed, 11 Oct 2023 06:44:29 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>i_am_gr00t.log</title>
            <url>https://velog.velcdn.com/images/i_am_gr00t/profile/e0e7c0f8-4457-47ba-adc6-16f31f8eaa6d/social_profile.png</url>
            <link>https://velog.io/</link>
        </image>
        <copyright>Copyright (C) 2019. i_am_gr00t.log. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/i_am_gr00t" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[[백준] 13164 행복 유치원 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-13164-%ED%96%89%EB%B3%B5-%EC%9C%A0%EC%B9%98%EC%9B%90-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-13164-%ED%96%89%EB%B3%B5-%EC%9C%A0%EC%B9%98%EC%9B%90-C</guid>
            <pubDate>Wed, 11 Oct 2023 06:44:29 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/547d8a62-2c49-4a02-9165-1dff49012831/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/13164">13164번: 행복 유치원</a></p>
<h1 id="풀이">풀이</h1>
<p> 먼저 티셔츠 만드는 비용의 합을 구하는 방법을 알아봅시다.</p>
<p> 입력으로 주어지는 원생들의 키는 정렬되어 있습니다. 
 총 n 명에 대해서 각 키를
 $$
 a_1, ; a_1, ;a_2, ; \cdots ,; a_{n}
 $$
이라 한다면
모든 원생이 한 조일 경우, $cost_1 = a_n - a_1$ 입니다.</p>
</br>

<p>만약 i번째와 i+1 번째 원생 사이를 기준으로 두 조로 나누게 된다면 각 조의 (마지막 - 처음)을 더하여 비용을 구할 수 있습니다.
$$
cost_2 = a_i-a_1 ;+ ;a_n-a_{i+1}
$$
이때 식의 순서를 조금 바꾸어보면
$$
cost_2 = a_n-a_1 ;+ ;a_i-a_{i+1} = cost_1 ; - ; (a_{i+1}-a_{i})
$$
이렇게 변형할 수 있고, 이는 한 조로 나눌때의 비용에 i+1번째원생, i번째 원생의 키 차이를 뺀 값이 됩니다.</p>
<p>마찬가지로 
$$
\begin{aligned}
cost_3 &amp;= cost_2 - (a_{j+1}-a_j)\
&amp;= cost_1-(a_{i+1}-a_{i})-(a_{j+1}-a_j)
\end{aligned}
$$</p>
<p>이때 $cost_3$이 최소가 되고 싶다면 $(a_{i+1}-a_{i})-(a_{j+1}-a_j)$ 값이 최대가 되어야 합니다.</p>
<p>이를 편하게 보기 위해 모든 $i$에 대해 $a_i - a_{i+1}$의 값을 저장하여 정렬한 배열을 $b_i$를 정의하겠습니다. 
($b_1 &gt; b_2 &gt; b_3 ;\cdots &gt; b_{n-1})$</p>
</br>

<p>이제 최소일 때의 $cost_3$, 즉  $minCost_3$를 정의하면
$$
minCost_3 = cost_1 - b_1 - b_2
$$</p>
<p>k로 일반화하면 
$$
minCost_k = cost_1;-b_1;-b_2-\cdots -b_{k-1} 
$$</p>
</br>

<p>정리하자면 각 이웃한 원생들의 차이를 저장하는 배열을 만들고,
가장 큰 수부터 차례로 하나씩 뽑기 위해 정렬합니다.</p>
<p>정렬된 값에서 큰 순서대로 k-1 번째까지의 수를 <code>a[n-1]-a[0]</code> 에 모두 빼주면 k개의 조를 나누었을 때의 최소비용을 구할 수 있습니다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;

using namespace std;

int n, k;
vector&lt;int&gt; arr;

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

    cin &gt;&gt; n &gt;&gt; k;
    arr.reserve(n);
    for(int i=0; i&lt;n; ++i)
    {
        int temp;
        cin &gt;&gt; temp;
        arr.push_back(temp);
    }

    vector&lt;int&gt; intervals;
    intervals.reserve(n-1);
    for (int i=1; i&lt;n; ++i)
        intervals.push_back(arr[i] - arr[i-1]);

    sort(intervals.begin(), intervals.end());

    for (int i=0; i&lt;k-1; ++i) // k개의 조를 나누기 위해서 k-1개의 칸막이가 필요하다.
        intervals.pop_back();

    int cost = 0;
    for (int interval : intervals)
        cost += interval;

    cout &lt;&lt; cost &lt;&lt; endl;
    return 0;
}</code></pre>
<blockquote>
<p>너무 직관적으로 풀이를 떠올린것 같아 일부러 최대한 논리적으로 풀이를 작성해보았다.</p>
</blockquote>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 마지막 팩토리얼 수 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-%EB%A7%88%EC%A7%80%EB%A7%89-%ED%8C%A9%ED%86%A0%EB%A6%AC%EC%96%BC-%EC%88%98-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-%EB%A7%88%EC%A7%80%EB%A7%89-%ED%8C%A9%ED%86%A0%EB%A6%AC%EC%96%BC-%EC%88%98-C</guid>
            <pubDate>Fri, 06 Oct 2023 14:32:26 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/0ca90065-1f30-41b0-8016-a26766163321/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/2553">2553번: 마지막 팩토리얼 수</a></p>
<h1 id="풀이">풀이</h1>
<p>팩토리얼이 커진다면 2와 5가 계속해서 많이 곱해지기 때문에 가장 낮은 자리 수는 0으로 고정됩니다.
하지만 구해야 하는 수는 0이 아닌 가장 낮은 자리 수 이기 때문에 0을 제거하기 위해 10이 되는 2와 5가 곱해지는 경우들을 제거해야 합니다.</p>
<p>이를 위해, 우선 팩토리얼을 5개씩 끊어서 계산합니다.
$$
(1 \times 2 \times 3 \times 4 \times 5) \times (6 \times 7 \times 8 \times 9 \times 10) \times (11 \times 12\times 13 \times 14 \times 15)
$$
</br></p>
<p>그 다음 5의 배수들을 맨 앞으로 넘겨 묶어 줍니다.
$$
(5 \times 10 \times 15) \times ( 1 \times 2\times 3 \times 4) \times(6 \times 7 \times 8 \times 9) \times ( 11 \times 12 \times 13 \times 14)
$$
</br></p>
<p>5의 배수끼리 묶은 수를 $5^n \times n!$로 표현합니다.
$$
(5^3 \times3!) \times (1 \times 2 \times 3\times 4) \times ( 6 \times 7 \times 8 \times 9) \times (11 \times 12 \times 13 \times 14)
$$
</br></p>
<p>놀랍게도 4개씩 묶은 수들은 모두 곱하면 4로 끝나게 됩니다. 따라서 아래와 같이 식을 변형할 수 있습니다.
$$
(5^3 \times3!) \times (4) \times (4) \times (4) = (5^3 \times3!) \times 4^3=(5^3 \times3!) \times 2^3 \times 2^3
$$
</br></p>
<p>10을 날리기 위해 식을 또 변형하면
$$
10^3 \times 3! \times 2^3 = 3! \times 2^3
$$
즉, 5의 배수 팩토리얼의 0이 아닌 가장낮은 자리수는 $n! \times 2^n$ 형태로 나타낼 수 있습니다.
또 2의 제곱수의 가장 낮은 자리수는 2, 4, 8, 6, 2, 4 ,8, 6 ,... 으로 반복되므로
$$
n! \times 2^{n\mod4}
$$
가 최종 공식이 됩니다.</p>
<p>이때 $n$은 <code>입력된 수 / 5</code> 입니다.</p>
</br>

<p>그렇다면 5의 배수가 아닌 경우는 어떻게 구해야 할까요?
예를 들어 $17!$ 을 구해야 한다면 간단히 $15! \times 16 \times 17$의 가장 낮은 자리수를 구하면 됩니다. $15!$을 공식으로 간단히 구할 수 있으므로 1의 자리수만을 곱해주면 답을 구할 수 있습니다.</p>
</br>

<p>공식을 보면 알겠지만 $n!$을 구하기 위해서는 $(\frac{n}{5})!$을 구해야합니다.
재귀 함수를 사용하여 top-down 방식으로도 구할 수 있고,
반복문을 통해 $1!$부터 $n!$까지 bottom-up 방식으로도 구할 수 있습니다.</p>
<h1 id="코드">코드</h1>
<p><strong>Bottom-up</strong></p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;cmath&gt;

using namespace std;

int main() 
{
    int N;
    cin &gt;&gt; N;

    int dp[20001];
    dp[0] = dp[1] = 1;
    dp[2] = 2;
    dp[3] = 6;
    dp[4] = 4;

    for (int i = 5; i &lt;= N; i++) {
        if (i % 5 == 0) 
        {
            int q = i / 5;
            dp[i] = ((int)pow(2, q % 4) * dp[q]) % 10;
        } 
        else 
        {
            int before = (i / 5) * 5;
            int total = 1;
            for (int j = before+1; j &lt;= i; j++) 
            {
                total *= (j % 10);
            }
            total *= dp[before];
            dp[i] = total % 10;
        }
    }

    cout &lt;&lt; dp[N] &lt;&lt; endl;
    return 0;
}</code></pre>
<p><strong>Top-down</strong></p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;cmath&gt;

using namespace std;

int getQPac(int n)
{
    switch(n)
    {
        case 0:
        case 1:
            return 1;
        case 2:
            return 2;
        case 3:
            return 6;
        case 4:
            return 4;

        default:
            int q= n / 5;
            int qtime5 = q * 5;

            int ret = getQPac(q) * pow(2, q%4);
            for (int i=qtime5+1; i &lt;= n; ++i)
            {
                ret *= i % 10;
            }
            return ret % 10;
    }
}

int main()
{
    int n;
    cin &gt;&gt; n;

    int answer = getQPac(n);

    cout &lt;&lt; answer &lt;&lt; endl;
    return 0;
}</code></pre>
<h1 id="참고">참고</h1>
<p><a href="https://steady-coding.tistory.com/322">https://steady-coding.tistory.com/322</a>
<a href="https://www.youtube.com/watch?v=RmENut3ZmnM">https://www.youtube.com/watch?v=RmENut3ZmnM</a>
<a href="https://www.campusgate.in/2013/10/finding-right-most-non-zero-digit-of.html">https://www.campusgate.in/2013/10/finding-right-most-non-zero-digit-of.html</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 2239 스도쿠 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-2239-%EC%8A%A4%EB%8F%84%EC%BF%A0-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-2239-%EC%8A%A4%EB%8F%84%EC%BF%A0-C</guid>
            <pubDate>Thu, 05 Oct 2023 01:29:50 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/e2e7d13d-1510-44c5-84aa-3e5d0d38f256/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/2239">2339번 스도쿠</a></p>
<h1 id="풀이">풀이</h1>
<p>답이 여러개인 경우도 고려해야 하기 때문에 백트래킹으로 모든 경우의 수를 살펴봐야합니다.</p>
<p>우선 스도쿠의 규칙에 의해 중복된 숫자가 존재하지 않도록 각 행, 열, 3x3 사각형에 해당하는 중복 확인을 위한 배열을 만듭니다. 숫자가 스도쿠판에 하나 채워지면 해당 위치의 행, 열, 사각형을 의미하는 배열의 숫자를 체크해둡니다.</p>
<p>답이 여러개일 경우 사전식으로 가장 앞서는 것을 출력해야 하므로 왼쪽위부터, 1부터 채워넣어보며 완성이 되는 경우를 바로 답으로 채택합니다. 이를 위해 백트래킹 함수의 리턴을 bool로 하여 어떤 경우가 true를 리턴한다면 그 답을 채택하도록 하였습니다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;memory.h&gt;

using namespace std;

int sudoku[9][9];
bool row[9][10];
bool col[9][10];
bool square[3][3][10];

bool dfs(int idx)
{
    if (idx == 9*9)
        return true;

    int x = idx / 9;
    int y = idx % 9;

    if (sudoku[x][y] != 0)
        return dfs(idx+1);

    for (int i=1; i&lt;10; ++i)
    {
        if (row[x][i] || col[y][i] || square[x/3][y/3][i])
            continue;

        row[x][i] = true;
        col[y][i] = true;
        square[x/3][y/3][i] = true;

        sudoku[x][y] = i;
        if (dfs(idx+1))
        {
            return true;
        }
        sudoku[x][y] = 0;

        row[x][i] = false;
        col[y][i] = false;
        square[x/3][y/3][i] = false;
    }

    return false;

}

int main()
{
    memset(row, false, sizeof(row));
    memset(col, false, sizeof(col));
    memset(square, false, sizeof(square));

    for (int i=0; i&lt;9; ++i)
    {
        string input;
        cin &gt;&gt; input;
        for (int j=0; j&lt;9; ++j)
        {
            int val = (int)input[j] - &#39;0&#39;;
            sudoku[i][j] = val;

            row[i][val] = true;
            col[j][val] = true;
            square[i/3][j/3][val] = true;
        }
    }

    dfs(0);

    for (int i=0; i&lt;9; ++i)
    {
        for (int j=0; j&lt;9; ++j)
        {
            cout &lt;&lt; sudoku[i][j];
        }
        cout &lt;&lt; endl;
    } 
    return 0;
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 1799 비숍 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-1799-%EB%B9%84%EC%88%8D-C-g8jtit9j</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-1799-%EB%B9%84%EC%88%8D-C-g8jtit9j</guid>
            <pubDate>Sat, 30 Sep 2023 11:57:35 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/94f652ef-9290-43c9-a5e0-d5853c63455a/image.png" alt="">
<img src="https://velog.velcdn.com/images/i_am_gr00t/post/6d4896de-f772-49e7-8724-7afe1b334482/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/1799">1799번: 비숍</a></p>
<h1 id="풀이">풀이</h1>
<p>문제를 보자마자 처음 든 생각은 &quot;그리디로 풀 수 있지 않을까?&quot; 였습니다. 색칠되지 않은 위치에 비숍을 놓았을 때 놓을 수 없어지는 비숍의 수를 우선순위로 하여 적은 것부터 놓게 된다면 문제를 해결할 수 있다고 생각했습니다. 하지만 모든 비숍의 우선순위 조건이 같은 경우 문제가 발생했습니다. 같을 경우 다음 우선순위를 무엇으로 잡아야하는지 알 수 없었기 때문에 그리디로 해결할 수 없었습니다.</p>
<p>따라서 백트래킹으로 모든 경우의 수를 확인해야 합니다.
체스판 임의의 칸에 비숍을 두는 경우, 두지 않은 경우를 고려하여 마지막 칸 차례까지 확인 후 가장 비숍을 많이 둔 경우를 채택합니다.</p>
<p>하지만 n*n 크기의 체스판을 하나씩 돌며 확인하면 $2^{100}$으로 엄청난 시간이 걸리게 됩니다. </p>
<p>체스판에서 흰색 칸에 있는 비숍은 어떻게 움직여도 절대 검은색 칸으로 이동할 수 없습니다. 비숍의 위치는 같은 색상 칸에만 영향을 받기 때문에 흰색칸과 검은색칸을 독립적으로 탐색하여 시간비용을 줄일 수 있습니다.</p>
<p>어떤 위치에 비숍을 두어도 되는지 확인하는 방법은 대각선 방향 위치 인덱스의 <code>x+y</code>, <code>x-y</code>값을 이용합니다.
어떤 위치의 오른쪽 위, 왼쪽 아래 방향으로는 <code>x+y</code>의 값이 동일합니다.
어떤 위치의 왼쪽 위, 오른쪽 아래 방향으로는 <code>x-y</code>의 값이 동일합니다.</p>
<p>체스판의 대각선방향으로 비숍이 있는지 없는지 확인하기 위해 x+y, x-y의 값이을 인덱스로 하는 배열의 <code>true</code>인지 <code>false</code>인지를 확인하여 판단할 수 있습니다.
n*n 크기라면 필요한 개수는 <code>n*2</code>개가 필요합니다. 오른쪽 위 방향, 오른쪽 아래 방향 두가지를 준비하여 각각 x+y, x-y+(n-1)로 인덱스를 설정합니다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

int n;
vector&lt;vector&lt;bool&gt;&gt; board;
vector&lt;bool&gt; incr;
vector&lt;bool&gt; decr;
int odd = 0;
int even = 0;
// int answer[2] = {0, 0};

int max(int a, int b) { return a &gt; b ? a : b; }

void dfs(int x, int y, int cnt, bool isOdd)
{
    if (y &gt;= n)
    {
        x += 1;
        if(y % 2 == 0) y = 1;
        else y = 0;
    }
    if (x &gt;= n)
    {
        // answer[isOdd] = max(answer[isOdd], cnt);
        int&amp; answer = isOdd ? odd : even;
        answer = max(answer, cnt);
        return;
    }

    if (board[x][y] &amp;&amp; !incr[x + y] &amp;&amp; !decr[x - y + n-1])
    {
        incr[x+y] = true;
        decr[x-y+n-1] = true;
        dfs(x, y+2, cnt+1, isOdd);
        incr[x+y] = false;
        decr[x-y+n-1] = false;
    }

    dfs(x, y+2, cnt, isOdd);
}

int main()
{
    cin &gt;&gt; n;
    board = vector(n, vector&lt;bool&gt;(n, false));
    incr = vector&lt;bool&gt;(n*2, false);
    decr = vector&lt;bool&gt;(n*2, false);
    for (int i=0; i&lt;n; i++)
    {
        for (int j=0; j&lt;n; ++j)
        {
            bool temp;
            cin &gt;&gt; temp;
            board[i][j] = temp;
        }
    }

    dfs(0, 0, 0, false);
    dfs(0, 1, 0, true);

    cout &lt;&lt; odd + even &lt;&lt; endl;
    return 0;
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 19236 청소년 상어 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-19236-%EC%B2%AD%EC%86%8C%EB%85%84-%EC%83%81%EC%96%B4-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-19236-%EC%B2%AD%EC%86%8C%EB%85%84-%EC%83%81%EC%96%B4-C</guid>
            <pubDate>Sat, 23 Sep 2023 11:43:11 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/f36ad7a7-f0e6-4fa0-a710-f42638436679/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/19236">19236번: 청소년 상어</a></p>
<h1 id="풀이">풀이</h1>
<p>상어가 움직일 수 있는 위치가 여러곳이고, 그에따라 상어가 먹을 수 있는 물고기의 번호합이 달라집니다. 모든 경우의 수를 비교하기 위해 백트래킹을 이용하여 탐색합니다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

struct Fish
{
    pair&lt;int, int&gt; pos;
    int dir;
    bool isAlive = true;
};
int dedug = 0;

vector&lt;pair&lt;int, int&gt;&gt; direction { {-1, 0}, {-1, -1}, {0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1} };

bool OOB(int x, int y)
{
    return x &lt; 0 || x &gt;= 4 || y &lt; 0 || y &gt;= 4;
}

int max(int a, int b) { return a &gt; b ? a : b; }

void fishMove(vector&lt;vector&lt;int&gt;&gt;&amp; bowl, vector&lt;Fish&gt;&amp; fishes)
{
    for (int i=1; i&lt;=16; ++i)
    {
        if (!fishes[i].isAlive)
            continue;

        pair&lt;int, int&gt; pos = fishes[i].pos;
        int dir = fishes[i].dir;

        int nx = pos.first + direction[dir].first;
        int ny = pos.second + direction[dir].second;
        while (OOB(nx, ny) || bowl[nx][ny] == 0)
        {
            dir = (dir + 1) % 8;

            nx = pos.first + direction[dir].first;
            ny = pos.second + direction[dir].second;
        }

        int temp = bowl[nx][ny];
        bowl[nx][ny] = i;
        fishes[i].pos = {nx, ny};
        fishes[i].dir = dir;

        bowl[pos.first][pos.second] = temp;
        if (temp != -1)
        {
            fishes[temp].pos = pos;
        }
    }
}

int getMaxFish(vector&lt;vector&lt;int&gt;&gt;&amp; bowl, vector&lt;Fish&gt;&amp; fishes)
{
    int dir = fishes[0].dir;
    pair&lt;int, int&gt; pos = fishes[0].pos;
    vector&lt;pair&lt;int, int&gt;&gt; nexts;
    int nx = pos.first + direction[dir].first;
    int ny = pos.second + direction[dir].second;
    while (!OOB(nx, ny))
    {
        nexts.push_back({nx, ny});

        nx += direction[dir].first;
        ny += direction[dir].second;
    }

    int maxFish = 0;
    for (auto next : nexts)
    {
        vector&lt;vector&lt;int&gt;&gt; nbowl = bowl;
        vector&lt;Fish&gt; nfishes = fishes;

        int die = bowl[next.first][next.second];
        if (die == -1)
            continue;

        nfishes[0] = fishes[die];
        nfishes[die].isAlive = false;
        nbowl[next.first][next.second] = 0;
        nbowl[pos.first][pos.second] = -1; // 기존 상어 위치에 죽은 물고기 넣기

        fishMove(nbowl, nfishes);

        maxFish = max(maxFish, getMaxFish(nbowl, nfishes) + die);
    }
    return maxFish;
}

int main() 
{
    vector&lt;vector&lt;int&gt;&gt; bowl(4, vector&lt;int&gt;(4));
    vector&lt;Fish&gt; fishes(17);
    for (int i=0; i&lt;4; ++i)
    {
        for (int j=0; j&lt;4; ++j)
        {
            int n, d;
            cin &gt;&gt; n &gt;&gt; d;
            bowl[i][j] = n;
            fishes[n] = {{i, j}, d-1};
        }
    }

    int first = bowl[0][0];
    bowl[0][0] = 0; // 0번은 상어
    fishes[0] = fishes[first];
    fishes[first].isAlive = false;

    fishMove(bowl, fishes);

    int answer = getMaxFish(bowl, fishes) + first;

    cout &lt;&lt; answer &lt;&lt; endl;
    return 0;
}

/*
번호가 작은 물고기부터 이동

상어는 물고기가 없는 칸으로 이동할 수 없다.
*/</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 14442 벽 부수고 이동하기2 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-14442-%EB%B2%BD-%EB%B6%80%EC%88%98%EA%B3%A0-%EC%9D%B4%EB%8F%99%ED%95%98%EA%B8%B02-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-14442-%EB%B2%BD-%EB%B6%80%EC%88%98%EA%B3%A0-%EC%9D%B4%EB%8F%99%ED%95%98%EA%B8%B02-C</guid>
            <pubDate>Mon, 18 Sep 2023 07:11:31 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/ffd9ce19-4906-464f-bc65-fa73ce74c6a3/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/14442">14442번: 벽 부수고 이동하기2</a></p>
<h1 id="풀이">풀이</h1>
<p>목적지 까지의 최단 거리를 알기 위해 bfs 탐색을 활용합니다. 그런데 벽을 k개 까지 부술 수 있습니다. 따라서 bfs 탐색 queue에 현재 위치뿐만 아니라 지금까지 몇개의 벽을 부셨는지에 대한 값도 저장해야 합니다.
그에 따라 현재 위치까지 도달하기 위해 몇개의 벽을 부셨는지를 저장하는 배열도 필요합니다.
<code>dist[i][j][k]</code> : i,j 에 도착하기 위해 k개의 벽을 부쉈을 때의 최소거리</p>
<p>bfs 탐색을 하며 맵의 값이 0인 경우와 1인 경우를 다르게 처리합니다. 현재 부순 벽의 개수를 <code>ck</code>라 할때 </p>
<p>맵의 값이 0인 경우 벽을 부수지 않고 지나갈 수 있기 때문에 <code>ck</code>값을 올리지 않고 일반적인 bfs 탐색하듯이 처리할 수 있습니다. 단순히 다음 위치가 맵의 경계를 넘어갔는지(out of boundary), 다음 위치를 이미 탐색하여 더빠른 수가 있었는지에 대해 조건을 확인합니다.</p>
<p>맵의 값이 1인 경우 벽을 부숴야 합이다. 이때 조건이 하나 추가되어야 합니다. <code>ck</code>의 값이 <code>k</code>보다 작지 않은 경우에 <code>ck+1</code>로 dist 배열에 접근 할때 문제가 발생되기 때문에 <code>continue</code>로 넘어갑니다. 
인덱스 문제를 해결했다면 <code>dist[nextI][nextJ][ck+1] = dist[i][j][ck] + 1</code>로 다음 위치의 최소 거리 값을 저장할때 <code>ck+1</code>의 벽을 부순 위치에 기록해야 합니다.
또한 다음 큐에 push 할때에도 <code>queue.push({nextI, nextJ, ck+1})</code>로 하여 벽 하나를 부순 처리를 해야 합니다. </p>
<p>bfs 탐색이 끝나면 <code>dist[i][j][0] ~ dist[i][j][k]</code>의 수들 중에서 최소값을 선택하여 출력하면 됩니다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;queue&gt;

using namespace std;

struct State
{
    int x;
    int y;
    int k=0;
};

int n, m, k;
vector&lt;vector&lt;char&gt;&gt; map;
vector&lt;vector&lt;vector&lt;int&gt;&gt;&gt; dist;
vector&lt;int&gt; dx {0, 0, -1, 1};
vector&lt;int&gt; dy {1, -1, 0, 0};

int min(int a, int b) { return a &lt; b ? a : b; }

bool OOB(int x, int y)
{
    return x &lt; 0 || x &gt;= n || y &lt; 0 || y &gt;= m;
}

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

    cin &gt;&gt; n &gt;&gt; m &gt;&gt; k;
    map.resize(n, vector&lt;char&gt;(m));
    dist.resize(n, vector&lt;vector&lt;int&gt;&gt;(m, vector&lt;int&gt;(k+1, 0))); // map[i][j]까지 가기위해 k 개 벽을 부순상태
    for (int i=0; i&lt;n; ++i)
    {
        for (int j=0; j&lt;m; ++j)
        {
            cin &gt;&gt; map[i][j];
        }
    }

    queue&lt;State&gt; q;
    q.push({0,0,0});
    dist[0][0][0] = 1; // 출발지점도 카운트에 포함

    while (!q.empty())
    {
        int cx = q.front().x;
        int cy = q.front().y;
        int ck = q.front().k;
        q.pop();

        for (int d=0; d&lt;4; ++d)
        {
            int nx = cx + dx[d];
            int ny = cy + dy[d];

            if (OOB(nx, ny))
                continue;

            if (map[nx][ny] == &#39;0&#39;)
            {
                if (dist[nx][ny][ck] != 0)
                    continue;

                q.push({nx, ny, ck});
                dist[nx][ny][ck] = dist[cx][cy][ck] + 1;
            }
            else 
            {
                if (ck &gt;= k)
                    continue;

                if (dist[nx][ny].at(ck+1) != 0)
                    continue;

                q.push({nx, ny, ck+1});
                dist[nx][ny][ck+1] = dist[cx][cy][ck] + 1;

            }
        }
    }

    int answer = INT32_MAX;
    for (auto a : dist[n-1][m-1])
    {
        if (a == 0)
            continue;

        answer = min(a, answer);
    }
    if (answer == INT32_MAX)
        answer = -1;

    cout &lt;&lt; answer &lt;&lt; endl;

    return 0;
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 8980 택배 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-8980-%ED%83%9D%EB%B0%B0-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-8980-%ED%83%9D%EB%B0%B0-C</guid>
            <pubDate>Sat, 16 Sep 2023 10:58:46 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/695a029c-afbb-4b51-9d98-b07503948237/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/8980">8980번: 택배</a></p>
<h1 id="풀이">풀이</h1>
<p>사실 이 문제가 왜 그리디 알고리즘으로 해결이 가능한지 증명하지 못했습니다. 하지만 그럼에도 불구하고 할당받은 문제이기 때문에 풀이를 작성합니다.</p>
</br>

<p>이 문제를 <a href="https://www.acmicpc.net/problem/1931">[백준]1931번: 회의실 배정</a>문제에 대입해 봅시다. 그렇다면 이 문제는 회의실이 C 만큼 있다고 할 수 있습니다. 보내는 마을은 회의 시작 시간, 받는 마을은 회의 끝나는 시간이라 할 수 있겠네요. 목적은 마찬가지로 가장 많은 회의를 배정하는 것입니다.</p>
<p>회의실이 많아졌지만 똑같습니다. 각 회의실에 가장 많은 회의를 배정하기 위한 최적의 해는 그리디 알고리즘으로 구할 수 있습니다. 회의가 끝나는 시간(받는 마을)이 시작 점과 가까운 순서대로 정렬한 후 그 순서대로 처리해주면 됩니다.</p>
<p>하지만 회의실이 많아졌다고 회의실 수 만큼 반복하기보단 다른 방법을 사용해 봅시다.</p>
<p>각 시간과 시간 사이에 남은 회의실 수를 저장합니다. 1<del>2 사이를 구간1, 2</del>3 사이를 구간2, ... 라고 한다면 초기의 구간별 남은 회의실 수는 구간1 = C, 구간2 = C, ... 가 됩니다.</p>
<p>예를 들어 C = 40, 1<del>2 시간 까지 10개의 회의실을 사용한다면 <code>구간1 = 30</code>이 됩니다. 
추가로 1</del>3 시간동안 20개의 회의실을 사용한다면 <code>구간1 = 10</code>, <code>구간2 = 20</code>이 됩니다.</p>
<p>그렇다면 1<del>4시간동안 30개의 회의실을 사용하려 한다면? 구간1, 구간2, 구간3 모두 30 이상이어야 하는데 구간1과 구간2의 남은 회의실이 모잘라 30을 모두 할당할 수 없습니다. 따라서 <strong>최소값</strong>인 구간1의 남은 10만큼만 할당할 수 있고 10개의 회의실을 사용하게 된다면 <code>구간1 = 0</code>, <code>구간2 = 10</code>, <code>구간3 = 30</code>이 됩니다. 
마찬가지로 2</del>4 시간에 20개의 회의실이 필요해도 구간2와 구간3의 최소값 만큼만 할당할 수 있습니다.</p>
<p>구현은 방금 설명한 것처럼 구간마다의 남은 회의실을 고려하여 회의실 배정을 해야합니다.
그렇다면 가장 많은 회의실을 사용하기 위해 끝나는 시간으로 정렬한 순서대로 하나씩 처리하면 가장 많은 회의실을 배정할 수 있게 되겠네요.</p>
<p>회의실 배정 문제로 대입해서 풀었지만 
회의 시작 시간 : 보내는 마을
회의 끝나는 시간 : 받는 마을
회의 개수 : 박스 개수
로 바꾸어 이번 문제를 해결할 수 있습니다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;

using namespace std;

struct Delivery
{
    int from;
    int to;
    int box;

    bool operator&lt;(Delivery input)
    {
        if (this-&gt;to == input.to)
            return this-&gt;from &lt; input.from;
        else
            return this-&gt;to &lt; input.to;
    }
};

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

    int n, m, capacity;

    cin &gt;&gt; n &gt;&gt; capacity;
    cin &gt;&gt; m;

    vector&lt;int&gt; sizes(n+1, capacity);
    vector&lt;Delivery&gt; delivery(m);

    for (int i=0; i&lt;m; ++i)
    {
        int a, b, c;
        cin &gt;&gt; a &gt;&gt; b &gt;&gt; c;
        delivery[i] = {a, b, c};
    }
    sort(delivery.begin(), delivery.end());

    int answer = 0;
    for (auto del : delivery)
    {
        int minSize = INT32_MAX; // 각 마을 중 가장 용량이 적게남은 
        for (int i=del.from; i&lt;del.to; ++i)
            minSize = min(minSize, sizes[i]);

        int curBox = min(minSize, del.box);
        for (int i=del.from; i&lt;del.to; ++i)
            sizes[i] -= curBox;

        answer += curBox;
    }

    cout &lt;&lt; answer &lt;&lt; endl;
}</code></pre>
<p>문제의 예제2를 보면 <code>2 5 70</code>, <code>3 4 40</code>이 주어집니다. 위에서 언급했듯이 도착 마을 순서로 정렬하게 되면 <code>3 4 40</code> 박스를 먼저 싣고 <code>2 5 70</code> 박스를 나중에 싣게 됩니다. 트럭은 최대 60까지만 싣을 수 있으니 <code>2 5 20</code>이 되겠네요. 어짜피 5번 마을까지 가는데 60까지만 배송이 가능합니다. <code>3 4 40</code> + <code>2 5 20</code> == <code>2 5 60</code>입니다.</p>
<h1 id="참고">참고</h1>
<p><a href="https://www.acmicpc.net/board/view/125942">https://www.acmicpc.net/board/view/125942</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 21609 상어 중학교 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-21609-%EC%83%81%EC%96%B4-%EC%A4%91%ED%95%99%EA%B5%90-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-21609-%EC%83%81%EC%96%B4-%EC%A4%91%ED%95%99%EA%B5%90-C</guid>
            <pubDate>Fri, 15 Sep 2023 15:22:00 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/f1a2f9db-4b8f-4402-bf40-b0b64b8118fc/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/3d52e759-b64e-454b-bd77-e71bdea15617/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/21609">21609번: 상어 중학교</a></p>
<h1 id="풀이">풀이</h1>
<p>bfs를 사용하는 구현문제 입니다. 알고리즘은 복잡하지 않아 구현만 잘하면 풀 수 있었네요.</p>
<p>문제의 오토플레이가 요구하는 4가지 기능을 구현해야 합니다.</p>
<ol>
<li>가장 큰 블록그룹 찾기</li>
<li>찾은 블록그룹 삭제하기</li>
<li>중력 작용하기</li>
<li>격자 반시계로 90도 회전하기</li>
</ol>
</br>

<p><strong>1. 가장 큰 블록그룹 찾기</strong>
bfs탐색을 통해 같은 색상 블록의 그룹을 찾으면 되겠습니다.</p>
<p>무지개 블록은 주의해야 하는데, 크기가 같은 블록 그룹이 생길 수 있기 때문에 무지개 블록을 탐색하게 되면 따로 vector에 모아두었다가 그 개수를 활용해야 합니다.
또 무지개 블록은 한 색상에 대해 탐색할때 탐색이 되어도, 다른 색상블록에 의해 다시 탐색될 수 있어야 하기 때문에 한가지 색상블록에 대한 bfs 탐색이 끝난 뒤 vector에 모아둔 무지개 블록들의 <code>visited</code>를 <code>false</code>로 변경해야 합니다.</p>
<p>bfs 시작점을 전체 격자의 왼쪽 위 부터 오른쪽 아래 순서로 결정 하기 때문에 시작점이 기준블록이 됩니다. 또한 자연스럽게 크기가 같고 무지개 블록의 개수도 같은 블록 그룹이 생긴다면 나중에 탐색된 그룹을 선택하면 되겠네요.</p>
</br>

<p><strong>2. 찾은 블록그룹 삭제하기</strong>
1번에서 찾은 그룹을 차례대로 삭제하면 됩니다. 이때 저는 삭제된 블록의 위치를 <code>-2</code>로 표현 하였는데, 몇가지 장점이 있습니다.</p>
<p>bfs 시작점을 찾을 때 <code>블록표현값 &lt; 1</code> 인 경우에만 시작점으로 선택하게 할 수 있습니다.
중력 작용 함수에서 중력이 작용할 블록은 <code>블록표현값 &lt; 0</code>으로 조건을 걸 수 있습니다.</p>
</br>

<p><strong>3. 중력 작용하기</strong>
중력이 정상적으로 작용하기 위해 가장 아래의 블록들부터 움직여야 합니다.
움직일 블록의 바로 밑블록부터 수직 아래 방향의 블록들을 탐색하는데, 빈블럭이 아닌경우(<code>-2</code>)를 만나게 될때까지 반복하며 한칸씩 아래로 탐색합니다. 빈 블록이 아닌 블록을 만나게 되면 그 위치의 한칸 위가 움직일 블록의 새로운 위치입니다.</p>
</br>

<p><strong>4. 회전하기</strong>
임시로 새로운 위치의 값들을 저장할 temp 격자를 만들어 <code>temp[i][j] = board[j][-i+n-1]</code>로 각블록들을 이동 시킨 뒤 <code>board = temp</code>로 변경하여 구현합니다.</p>
</br>

<p>필요한 기능을 모두 구현했다면 순서대로 배치하고 반복시킵니다.
종료 시점은 찾은 블록그룹의 개수가 2개 미만이라면 <code>break</code>를 통해 반복을 탈출합니다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;queue&gt;

using namespace std;

int n, m;
vector&lt;vector&lt;int&gt;&gt; board;

vector&lt;pair&lt;int, int&gt;&gt; dir { {0,1}, {0,-1}, {1,0}, {-1,0} };

bool OOB(int x, int y) { return x &lt; 0 || x &gt;= n || y &lt; 0 || y &gt;= n; }
int max(int a, int b) { return a &gt; b ? a : b; }

vector&lt;pair&lt;int, int&gt;&gt; bfs(int x, int y, vector&lt;vector&lt;bool&gt;&gt;&amp; visited, int&amp; rainbowCnt)
{
    vector&lt;pair&lt;int, int&gt;&gt; ret;
    int color = board[x][y];
    vector&lt;pair&lt;int, int&gt;&gt; rainbow;
    queue&lt;pair&lt;int, int&gt;&gt; q;

    q.push({x, y});
    ret.push_back({x, y});
    visited[x][y] = true;

    while (!q.empty())
    {
        int curX = q.front().first;
        int curY = q.front().second;
        q.pop();

        for (auto d: dir)
        {
            int nX = d.first + curX;
            int nY = d.second + curY;

            if (OOB(nX, nY) || visited[nX][nY])
                continue;

            if (board[nX][nY] != 0 &amp;&amp; board[nX][nY] != color)
                continue;

            if (board[nX][nY] == 0) // 무지개 블록은 bfs 탐색 후에 다른 색상의 블록이 사용할 수 있도록 visited = false로 변경해주어야한다.
                rainbow.push_back({nX, nY});
            visited[nX][nY] = true;
            ret.push_back({nX, nY});
            q.push({nX, nY});
        }
    }
    for (auto rb : rainbow)
        visited[rb.first][rb.second] = false;

    rainbowCnt = rainbow.size();
    return ret;
}

vector&lt;pair&lt;int, int&gt;&gt; findBlock(pair&lt;int, int&gt;&amp; pos) // return blockSize, pos = 블럭의 기준 위치
{
    vector&lt;vector&lt;bool&gt;&gt; visited(n, vector&lt;bool&gt;(n, false));
    vector&lt;pair&lt;int, int&gt;&gt; selected;
    int selectedRainbow = 0;

    for (int i=0; i&lt;n; ++i)
    {
        for (int j=0; j&lt;n; ++j)
        {
            if (board[i][j] &lt; 1) // 무지개, 검정 블록, -2는 비어있는 칸으로 처리
                continue;

            if (visited[i][j])
                continue;

            int bufferRainbow = 0;
            vector&lt;pair&lt;int, int&gt;&gt; buffer = bfs(i, j, visited, bufferRainbow);

            if (buffer.size() &lt; selected.size())
                continue;
            if (buffer.size() == selected.size())
            {
                if (bufferRainbow &lt; selectedRainbow)
                    continue;
            }

            selected = buffer;
            pos = {i, j};
            selectedRainbow = bufferRainbow;
        }
    }

    return selected;
}

int deletBlock(vector&lt;pair&lt;int, int&gt;&gt; blocks)
{
    int ret = 0;
    for (auto block : blocks)
    {
        int x = block.first;
        int y = block.second;

        board[x][y] = -2;
        ++ret;
    }

    return ret * ret;
}

void gravity()
{
    for (int i=n-1; i &gt;=0; --i)
    {
        for (int j=n-1; j&gt;=0; --j)
        {
            if (board[i][j] &lt; 0) // -1, -2 인 경우 넘어간다.
                continue;;

            int height = n-1;
            for (int h=i+1; h&lt;n; ++h)
            {
                if (board[h][j] != -2)
                {
                    height = h-1;
                    break;
                }
            }

            if (height != i)
            {
                board[height][j] = board[i][j];
                board[i][j] = -2;
            }
        }
    }
}

void rotate()
{
    vector&lt;vector&lt;int&gt;&gt; temp(n, vector&lt;int&gt;(n));
    for (int i=0; i&lt;n; ++i)
    {
        for(int j=0; j&lt;n; ++j)
        {
            temp[i][j] = board[j][-i+n-1];
        }
    }

    board = temp;
}

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

    cin &gt;&gt; n &gt;&gt; m;
    board.resize(n, vector&lt;int&gt;(n));
    for (int i=0; i&lt;n; ++i)
    {
        for (int j=0; j&lt;n; ++j)
        {
            cin &gt;&gt; board[i][j];
        }
    }

    int score = 0;
    while (true)
    {
        // find large block
            // block size &lt; 2 : break;
        pair&lt;int, int&gt; pos;
        vector&lt;pair&lt;int, int&gt;&gt; blocks = findBlock(pos);
        if (blocks.size() &lt; 2)
            break;

        // delet block, add score
        score += deletBlock(blocks);

        // gravity
        gravity();

        // rotate
        rotate();

        // gravity
        gravity();

    }

    cout &lt;&lt; score &lt;&lt; endl;
    return 0;
}

/*
기준 블록: 무지개가 아닌 행이 가장 작고, 열이 가장 작은 블록
찾을 블록: 크기가 가장 큰 블록 중, 무지개 블록이 많은 블록, 행이 가장 크고 열이 가장 큰 블록
격자는 반시계 회전
*/</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 1912 연속합 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-1912-%EC%97%B0%EC%86%8D%ED%95%A9-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-1912-%EC%97%B0%EC%86%8D%ED%95%A9-C</guid>
            <pubDate>Wed, 13 Sep 2023 11:06:19 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/e31ebc6b-91de-41c1-a108-ad55f7586505/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/1912">1912번: 연속합</a></p>
<h1 id="풀이">풀이</h1>
<p>문제를 풀기위해 모든 경우의 수를 비교하는 방법도 있지만, n &lt;= 100,000 이라는 조건 때문에 불가능합니다. 모든 경우의 수를 따지지 않고 해결하기위해 다이나믹프로그래밍을 이용하여 빠르게 해결할 수 있습니다.</p>
<p>우리가 구하고자 하는 최대 연속합을 이루는 수열을 <code>max_arr</code>라 하고, 0 &lt;= i &lt;= n이라 할때
수열이 i-1번째 수까지 있는 경우와 i번째 까지 있는 경우를 비교해 봅시다.
두 경우에 <code>max_arr</code>가 같을까요? i번째 수가 추가되어 달라질까요?</p>
<p>사실 2가지 경우 모두 존재할 수 있습니다. 두 경우 모두 생각해봅시다.
case1: i번째 수가 추가되어도 <code>max_arr</code>이 유지되는 경우
case2: i번째 수가 추가되며 <code>max_arr</code>가 변경되는 경우</p>
<p>case1이라면 i번째 수는 <code>max_arr</code>에 여전히 포함되지 않아 i-1번째 수까지 있는 경우와 같고
case2라면 i번째 수가 새로운 <code>max_arr</code>에 포함되어 i-1번째 수까지 있던 경우의 <code>max_arr</code>보다 커진 경우입니다.</p>
<p>case1과 case2를 결정하기 위해서는 i번째 수를 포함하는 최대 연속합을 찾고 그 값이 새로운 <code>max_arr</code>이 되는지 이전의 <code>max_arr</code>과 비교해야 합니다.</p>
<p>i번째 수를 포함하는 최대연속합을 <code>current_max[i]</code>에 저장하고 
i번째 수까지 있는 경우의 <code>max_arr</code>의 합을 저장하는 <code>total_max[i]</code>를 만들어 비교합니다.</p>
<ul>
<li>i-1번째 수까지 있는 경우의 <code>max_arr</code> : <code>total_max[i-1]</code></li>
<li>i번째 수를 포함하는 최대연속합 : <code>current_max[i]</code></li>
<li>i번째 수까지 있는 경우의 <code>max_arr</code> =&gt; <code>total_max[i] = max(total_max[i-1], current_max[i])</code></li>
</ul>
</br>

<p>그렇다면 <code>current_max[i]</code>는 어떻게 구해야 할까요?
입력으로 주어지는 수열에 음수도 포함되기 때문에 <code>current_max</code>는 단순히 누적합을 적을 수 없습니다.
<code>current_max[i-1]</code>이 음수인 경우 <code>current_max[i]</code>는 i번째 수 하나만 가지고 있는 것이 가장 큰 수일 것입니다.
이를 고려하여 <code>current_max[i] = max(current_max[i-1] + arr[i], arr[i])</code> 로 정리할 수 있습니다. (<code>arr[i]</code>는 i번째 수)</p>
<p></br> 정리하자면
<code>current_max[i]</code>: i번째 수를 포함하는 최대 연속합
<code>total_max[i]</code>: i번째 수를 추가했을 때의 전체 배열의 최대 연속합</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">import sys
n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))

total_max = {0:a[0]}
current_max = {0:a[0]}

for i in range(1,len(a)):
    current_max[i] = max(current_max[i-1]+a[i], a[i])
    total_max[i] = max(current_max[i], total_max[i-1])


print(total_max[n-1])</code></pre>
<h1 id="참고">참고</h1>
<p><a href="https://www.youtube.com/watch?v=GtqHli8HIqk">https://www.youtube.com/watch?v=GtqHli8HIqk</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 13398 연속합2 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-13398-%EC%97%B0%EC%86%8D%ED%95%A92-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-13398-%EC%97%B0%EC%86%8D%ED%95%A92-C</guid>
            <pubDate>Wed, 13 Sep 2023 08:31:57 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/753264de-18cb-4c35-a705-a6917e61e7d6/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/13398">13398번: 연속합2</a></p>
<h1 id="풀이">풀이</h1>
<p><a href="https://www.acmicpc.net/problem/2737">연속합</a> 문제에서 한가지 조건이 추가된 문제입니다. <a href="https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-1912-%EC%97%B0%EC%86%8D%ED%95%A9-C">연속합 문제 풀이</a>를 응용하여 이번 문제를 해결할 수 있습니다.</p>
<p>입력으로 주어진 배열이 <code>arr</code>이라 할때,
연속합 문제는 <code>currentMax[i] = max(currentMax[i-1] + arr[i], arr[i])</code>로 <code>currentMax</code> 배열을 만들어 그 중 가장 큰 값을 선택하면 되었습니다. (혹은 <code>totalMax</code> 배열을 만들어 전체 최대값을 저장한 후 <code>totalMax[n-1]</code>을 출력)</p>
<p>이번문제는 비교할 요소가 하나 늘었는데요
<code>currentMax</code>는 제외한 숫자가 없는 경우에서 현재 큰 수에 해당하니
배열 중 숫자를 하나 제거했을 때의 현재 큰 수도 저장할 필요가 있습니다.</p>
<p><code>excludeMax</code>배열을 만들어 <code>excludeMax[i] = max(currentMax[i-1], excludeMax[i-1]+arr[i])</code>를 저장합니다. </p>
<ul>
<li><code>currentMax[i-1]</code>: i번째 수가 빠진 경우</li>
<li><code>excludeMax[i-1]+arr[i]</code> : i번째 수 이전에 이미 빠진 수가 있는 경우</li>
</ul>
<p>위의 두 경우를 비교하여 더 큰 수를 <code>excludeMax</code> 배열에 저장합니다.</p>
<p>이제 마지막으로 최종 가장 큰 수를 찾기 위해 <code>currentMax</code>와 <code>excludeMax</code> 배열을 비교하여 그중 가장 큰 수를 찾습니다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

int max(int a, int b) { return a &gt; b ? a : b; }
int max(int a, int b, int c) { return max(a, max(b, c)); }

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

    int n;
    cin &gt;&gt; n;
    vector&lt;int&gt; arr(n);
    vector&lt;int&gt; currentMax(n, 0);
    vector&lt;int&gt; exclude(n, 0);
    for (int i=0; i&lt;n; ++i)
        cin &gt;&gt; arr[i];

    currentMax[0] = arr[0];
    exclude[0] = arr[0];

    for (int i=1; i&lt;n; ++i)
    {
        currentMax[i] = max(currentMax[i-1] + arr[i], arr[i]);
        //i번째 수가 빠진경우, i번째 수 전에 다른 수가 먼저 빠져있는 경우, a[i] 중 가장 큰 수를 저장
        exclude[i] = max(currentMax[i-1], exclude[i-1]+arr[i], arr[i]);
    }

    int maxVal = INT32_MIN;
    for (int i=0; i&lt;n; ++i)
        maxVal = max(maxVal, currentMax[i], exclude[i]);

    cout &lt;&lt; maxVal &lt;&lt; endl;
    return 0;
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 1918 후위 표기식 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-1918-%ED%9B%84%EC%9C%84-%ED%91%9C%EA%B8%B0%EC%8B%9D-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-1918-%ED%9B%84%EC%9C%84-%ED%91%9C%EA%B8%B0%EC%8B%9D-C</guid>
            <pubDate>Wed, 13 Sep 2023 07:48:04 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/311326ca-527d-4335-8677-a869941064e8/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/1918">1918번: 후위 표기식</a></p>
<h1 id="풀이">풀이</h1>
<p>문제에도 설명되어 있지만 후위 표기식은 피 연산자가 연산자 앞에 위치하며 연산자끼리의 우선순위를 비교하여 그 순서가 결정되고 괄호가 필요 없게 됩니다. 우선 순위가 높은 연산자가 낮은 연산자보다 먼저 배치됩니다. 중요한건 연산자들 사이의 우선순위를 비교하여 어떻게 순서대로 배치할 것인지가 되겠습니다.</p>
<p>사실 스택을 이용하면 쉽게 해결할 수 있습니다. 후위표기식의 계산 과정도 스택으로 구현할 수 있듯이 이 문제도 스택으로 구현할 수 있습니다. 
연산자의 종류와 우선순위를 담는 스택이 있을 때, 스택의 값과 새로운 연산자의 우선순위를 비교하여 새로운 연산자의 우선순위가 더 낮을 때까지 스택의 값을 출력하여 순서대로 정답 배열에 입력합니다.</p>
<p>문제에서는 괄호에 대한 우선순위도 고려해야 합니다. 
<code>(</code>가 주어진다면 앞으로 나올 연산자들의 우선순위를 +2 해주고, 
<code>)</code>가 주어진다면 다시 -2 해주어 관리합니다.
문제에서 항상 올바른 괄호짝을 입력으로 줄테니 우선순위가 꼬일 일은 없네요.</p>
<p>입력으로 주어진 식에 대해 모두 처리 했다면 스택에 남아있는 연산자들을 차례대로 출력하여 정답 배열에 입력합니다. </p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;string&gt;
using namespace std;

int main()
{
    string fomu;
    vector&lt;pair&lt;char, int&gt;&gt; operatorStack;
    vector&lt;char&gt; answer;
    cin &gt;&gt; fomu;

    int globalPri = 0;
    for (auto ch : fomu)
    {
        int localPri;
        switch(ch)
        {
            case(&#39;(&#39;):
                globalPri += 2;
                break;
            case(&#39;)&#39;):
                globalPri -= 2;
                break;

            case(&#39;+&#39;):
            case(&#39;-&#39;):
                localPri = 1;

                while (!operatorStack.empty() &amp;&amp; operatorStack.back().second &gt;= localPri + globalPri)
                {
                    answer.push_back(operatorStack.back().first);
                    operatorStack.pop_back();
                }
                operatorStack.push_back({ch, localPri+globalPri});
                break;

            case(&#39;*&#39;):
            case(&#39;/&#39;):
                localPri = 2;

                while (!operatorStack.empty() &amp;&amp; operatorStack.back().second &gt;= localPri + globalPri)
                {
                    answer.push_back(operatorStack.back().first);
                    operatorStack.pop_back();
                }
                operatorStack.push_back({ch, localPri+globalPri});
                break;

            default:
                answer.push_back(ch);
                break;
        }
    }
    while (!operatorStack.empty())
    {
        answer.push_back(operatorStack.back().first);
        operatorStack.pop_back();
    }

    for(auto a  : answer)
        cout &lt;&lt; a;
    cout &lt;&lt; endl;
    return 0;
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 11066 파일 합치기(C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-11066-%ED%8C%8C%EC%9D%BC-%ED%95%A9%EC%B9%98%EA%B8%B0C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-11066-%ED%8C%8C%EC%9D%BC-%ED%95%A9%EC%B9%98%EA%B8%B0C</guid>
            <pubDate>Sat, 09 Sep 2023 01:17:38 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/b1d21dcc-ac37-4dfc-9b4a-ab732ccfdd55/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/11066">11066번: 파일 합치기</a></p>
<h1 id="풀이">풀이</h1>
<p>이 문제는 파일끼리의 순서가 뒤섞이면 안된다. 항상 파일의 순서를 지켜 연속적인 두 파일만을 합칠 수 있다.</p>
<p>파일이 <code>i</code>번 ~ <code>j-1</code>번 까지의 파일을 모두 합치는데 비용을 <code>dp[i][j]</code>이라 한다면
점화식 <code>dp[i][j] = min(dp[i][k] + dp[k][j]) + sum(i~j-1)</code>을 이용해서 구할 수 있다.</p>
<ul>
<li><code>k</code>의 범위 : <code>i+1 &lt;= k &lt; j</code></li>
<li><code>sum(i ~ j-1)</code> : <code>i</code>부터 <code>j-1</code>까지의 누적합, 누적합 배열을 통해 <code>prefix(j) - prefix(i)</code>로 구할 수 있다.</li>
<li><code>dp[i][i] = 0</code> , <code>dp[i][i+1] = prefix(i+1) - prefix(i)</code>로 초기값을 설정한다.<ul>
<li><code>dp[i][i]</code>: 사실상 <code>k</code>값을 잘 조절한다면 참조할 일이 없다.</li>
<li><code>dp[i][i+1]</code>: 파일 하나를 합치는것은 불가능하지만 최소 비용으로 설정된다.</br>

</li>
</ul>
</li>
</ul>
<p><strong>재귀 함수</strong>
위의 점화식을 이용해서 다이나믹 프로그래밍으로 문제를 해결할 수 있다.
<code>dp(i, j) = min(dp(i, k) + dp(k, j) + prefix[j] - prefix[i])</code>를 통함 재귀호출로 
<code>dp(0, n)</code>의 리턴값을 출력하면 된다.
이때 모이제이션을 위한 2차원 배열을 사용하여 불필요한 중복 값을 줄인다.</p>
<p>재귀 함수를 사용하면 점화식을 직관적으로 사용할 수 있다는 장점이 있지만 함수를 호출하는데에 시간이 걸린다. 좀 더 빠른 방법을 원한다면 재귀함수 호출이 아닌 3중 반복문으로도 해결할 수 있다.</p>
</br>

<p><strong>반복문</strong>
2차원 배열을 순회하며 최정적으로 <code>dp[0][n]</code>의 위치에 알맞은 값을 넣어야 하는데 그 순서를 바로 알기 어려웠다.
<img src="https://velog.velcdn.com/images/i_am_gr00t/post/b4f9941b-63c2-4d42-979d-ba0fa709351d/image.png" alt=""></p>
<p>대각선 방향으로 탐색을 하며 자신의 인덱스에 맞는 값을 구하면 된다.
값을 구하기 위해 <code>k</code>는 <code>left+1 &lt;= k &lt; right</code>를 탐색하기에 3중 for문이 된다.</p>
<p>더 빠른 방법을 위해 Knuth Optimization을 사용하는 풀이도 있지만 아직 이해하지 못했다.</p>
<h1 id="코드">코드</h1>
<p><strong>재귀 함수</strong></p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

vector&lt;int&gt; arr;
vector&lt;vector&lt;int&gt;&gt; memo;
vector&lt;int&gt; prefix;

int min(int a, int b) { return a &lt; b ? a : b; }

int dp(int a, int b)
{
    if (memo[a][b] != INT32_MAX)
        return memo[a][b];

    if ( b-a == 1) 
        return memo[a][b] = 0;
    else if (b-a == 2)
        return memo[a][b] = prefix[b] - prefix[a];

    int minVal = INT32_MAX;

    for (int i=a+1; i&lt;b; ++i)
    {
        int dpA = dp(a, i);
        int dpB = dp(i, b);

        minVal = min( minVal, dpA + dpB + prefix[b] - prefix[a]);
    }

    return memo[a][b] = minVal;
}

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

    int testcase;
    cin &gt;&gt; testcase;
    while (testcase--)
    {
        int n;
        cin &gt;&gt; n;

        arr.resize(n);
        memo.assign(n+1, vector&lt;int&gt;(n+1, INT32_MAX));
        prefix.assign(n+1, 0);

        for (int i=0; i&lt;n; ++i)
            cin &gt;&gt; arr[i];

        for (int i=0; i&lt;n; ++i)
            prefix[i+1] = prefix[i] + arr[i];

        int answer = dp(0, n);

        cout &lt;&lt; answer &lt;&lt; &quot;\n&quot;;

        arr.clear();
        memo.clear();
        prefix.clear();
    }
    return 0;
}</code></pre>
<p><strong>for 반복문</strong></p>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;


int min(int a, int b) { return a &lt; b ? a : b; }

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

    int testcase;
    cin &gt;&gt; testcase;
    while (testcase--)
    {
        int n;
        cin &gt;&gt; n;

        vector&lt;int&gt; arr(n);
        vector&lt;int&gt; prefix(n+1, 0);
        vector&lt;vector&lt;int&gt;&gt; dp (n+1, vector&lt;int&gt;(n+1, 0));

        for (int i=0; i&lt;n; ++i)
            cin &gt;&gt; arr[i];

        for (int i=0; i&lt;n; ++i)
            prefix[i+1] = prefix[i] + arr[i];


        for (int i=2; i&lt;n+1; i++) // 파일 간격
        {
            for (int j=0; i+j&lt;n+1; ++j) // 반복할 파일 시작번호
            {
                int left = j;
                int right = i+j;
                int minVal = INT32_MAX;
                for (int mid = left+1; mid &lt; right; ++mid)
                {
                    minVal = min(minVal, dp[left][mid] + dp[mid][right] + prefix[right] - prefix[left]);
                }
                dp[left][right] = minVal;
            }
        }
        cout &lt;&lt; dp[0][n] &lt;&lt; &quot;\n&quot;;
    }
    return 0;
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 19235 모노미노도미노 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-19235-%EB%AA%A8%EB%85%B8%EB%AF%B8%EB%85%B8%EB%8F%84%EB%AF%B8%EB%85%B8-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-19235-%EB%AA%A8%EB%85%B8%EB%AF%B8%EB%85%B8%EB%8F%84%EB%AF%B8%EB%85%B8-C</guid>
            <pubDate>Fri, 08 Sep 2023 09:00:22 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/69c87280-e527-4894-a9f5-937ed2926bb3/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/19235">19235번: 모노미노도미노</a></p>
<h1 id="풀이">풀이</h1>
<p>별다른 알고리즘 없이 그냥 구현 문제였다.</p>
<p>파란색보드와 초록색보드가 서로대칭이다 보니 6X4 모양의 보드 하나로 퉁치고 계산했다.
파란색보드에 입력할 때 빨간보드의x,y 좌표를 서로 바꾸어 주면 된다.</p>
<p>두 보드 모두 6X4로 사용하기 때문에 두개를 붙인 블럭은 가로방향일 때만 신경써주면 된다.
물론 입력을 받을 때 t=2 혹은 t=3 인경우에 대칭이동을 시켜주어야 한다.
블럭이 세로인경우는 t=1 이 2번 호출된다고 간주하고 입력을 받았다.
가로 블럭의 경우 입력으로 주어진 x,y와 그에 종속적으로 x,y+1까지 고려해야 한다.
y 와 y+1 중 높이가 더 높은 위치에 해당하도록 한다.
계산은 항상 x,y에서만 진행하도록 x,y+1의 블럭은 type=3으로 하여 자체적으로 높이 계산을 못하도록 했다. 항상 x,y 위치에서만 연산하고 그 결과에 따라다니도록 했다. x,y에서 y+1의 위치까지도 고려해주므로 계산 결과는 문제가 없다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

int min(int a, int b) { return a &lt; b ? a : b; }

// 블럭들 가라앉히기
void setBlock(int type, int x, int y, vector&lt;vector&lt;int&gt;&gt;&amp; board)
{
    int newX = 5;
    board[x][y] = 0;

    for (int i=x+1; i&lt;6; ++i)
    {
        if (board[i][y] == 0)
            continue;

        newX = i-1;
        break;
    }

    if (type == 2)
    {
        board[x][y+1] = 0;
        for (int i=x+1; i&lt;6; ++i) // i의 시작 지점이 입력으로 받을 때와 블록이 사라져서 내려갈때가 다르다. 이건 입력부분에서 0으로 맞춰주면 될듯?
        {
            if (board[i][y+1] == 0)
                continue;

            newX = min(newX, i-1);
            break;
        }
    }

    board[newX][y] = type;
    if (type == 2)
        board[newX][y+1] = 3;
}

// 채워진 줄 찾고 삭제시키기
int checkRow(vector&lt;vector&lt;int&gt;&gt;&amp; board)
{
    int cnt = 0;
    for (int row=0; row&lt;6; ++row)
    {
        int cntZero = 0;
        for (int i=0; i&lt;4; ++i)
        {   
            if (board[row][i] == 0)
                ++cntZero;

        }

        if (cntZero &gt; 0)
            continue;

        for (int i=0; i&lt;4; ++i)
            board[row][i] = 0;

        cnt += 1;
    }

    return cnt;
}

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

    int score = 0;
    vector&lt;vector&lt;int&gt;&gt; blue = vector&lt;vector&lt;int&gt;&gt;(6, vector&lt;int&gt;(4));
    vector&lt;vector&lt;int&gt;&gt; green = vector&lt;vector&lt;int&gt;&gt;(6, vector&lt;int&gt;(4));

    int n; cin &gt;&gt; n;

    while (n--)
    {
        int t, x, y;
        cin &gt;&gt; t &gt;&gt; x &gt;&gt; y;
        switch(t)
        {
            case(1):
                setBlock(1, 0, y, green);
                setBlock(1, 0, x, blue);
                break;
            case(2):
                setBlock(2, 0, y, green);
                setBlock(1, 0, x, blue); // 혹시 몰라서 아래에 있는 블록 먼저 떨구기
                setBlock(1, 0, x, blue);
                break;
            case(3):
                setBlock(1, 0, y, green);
                setBlock(1, 0, y, green);
                setBlock(2, 0, x, blue);
                break;
        }

        // 줄 채운거 삭제 시키고 밑으로 내리기
        while (true)
        {
            int temp = checkRow(green);
            if (temp == 0)
                break;

            score += temp;
            for (int i=5; i&gt;= 0; --i) // 아랫줄부터 처리해야 한다.
                for (int j=0; j&lt;4; ++j)
                    if (green[i][j] == 1 || green[i][j] == 2)
                        setBlock(green[i][j], i, j, green);
        }

        while (true)
        {
            int temp = checkRow(blue);
            if (temp == 0)
                break;

            score += temp;
            for (int i=5; i&gt;=0; --i)
                for (int j=0; j&lt;4; ++j)
                    if (blue[i][j] == 1 || blue[i][j] == 2)
                        setBlock(blue[i][j], i, j, blue);
        }

        // 0, 1 초과분 밀어넣기
        for (int qq = 0; qq &lt; 2; ++qq)
            for (int i=0; i&lt;4; ++i)
            {
                if (green[1][i] != 0)
                {
                    for (int r=5; r&gt;=1; --r)
                    {
                        for (int c=0; c&lt;4; ++c)
                        {
                            green[r][c] = green[r-1][c];
                        }
                    }
                    for (int c=0; c&lt;4; ++c)
                        green[0][c] = 0;
                    break;
                }
            }

        for (int qq = 0; qq &lt; 2; ++qq)
            for (int i=0; i&lt;4; ++i)
            {
                if (blue[1][i] != 0)
                {
                    for (int r=5; r&gt;=1; --r)
                    {
                        for (int c=0; c&lt;4; ++c)
                        {
                            blue[r][c] = blue[r-1][c];
                        }
                    }
                    for (int c=0; c&lt;4; ++c)
                        blue[0][c] = 0;
                    break;
                }
            }

    }

    // 남아있는거 계산
    int left = 0;
    for (int i=0; i&lt;6; ++i)
    {
        for (int j=0; j&lt;6; ++j)
        {
            if (green[i][j] != 0)
                ++left;
            if (blue[i][j] != 0)
                ++left;
        }
    }

    cout &lt;&lt; score &lt;&lt; endl;
    cout &lt;&lt; left &lt;&lt; endl;
    return 0;
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 17143 낚시왕 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-17143-%EB%82%9A%EC%8B%9C%EC%99%95-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-17143-%EB%82%9A%EC%8B%9C%EC%99%95-C</guid>
            <pubDate>Thu, 07 Sep 2023 01:29:49 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/e01db834-d364-42d6-b7b8-3d83d7bc569f/image.png" alt="">
<img src="https://velog.velcdn.com/images/i_am_gr00t/post/a5987cc2-501d-435d-9ac8-a2cd0362428f/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/17143">17143번: 낚시왕</a></p>
<h1 id="풀이">풀이</h1>
<p>낚시왕이 오른쪽으로 한칸씩 이동하고 낚시하고, 상어들이 움직이고 를 반복하며 잡힌 상어의 크기의 총합을 출력하면 된다.</p>
<p>상어들이 이동할때 격자의 크기보다 speed가 큰 상어들이 있다. 이때 격자의 2배보다 큰 speed인경우 같은 자리, 같은 방향으로 돌아오게 되는 경우가 발생하여 굳이 불필요한 반복이 생긴다. 이를 미리 방지하기 위해 나머지 연산을 통해서 필요한 연산만을 한다.</p>
<p>상어는 위,아래 혹은 좌,우 방향으로만 움직이기 때문에 2방향으로 경우를 나누어 계산했다.
상어가 speed 만큼 이동 후의 위치가 0보다 작은지, 격자 최대값보다 큰지, 격자안에 알맞게 들어있는지를 나누어 처리했고 최종적으로 상어가 격자안에 위치할 때를 최종 위치로 했다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;

using namespace std;

// 상 하 우 좌
vector&lt;pair&lt;int, int&gt;&gt; direction { {0, 0}, {-1, 0}, {1, 0}, {0, 1}, {0, -1} };
int r, c, m;
vector&lt;vector&lt;struct Shark*&gt;&gt; board;

struct Shark
{
    Shark() {}
    ~Shark() {}

    int x;
    int y;
    int speed;
    int dir;
    int size;

    void setShark()
    {
        if (board[x][y] != nullptr)
            if (board[x][y]-&gt;size &gt; this-&gt;size)
                return;

        board[x][y] = this;
    }

    void move()
    {
        int max; // 1,2 : row가 최대움직일 거리 // 

        if ( dir &lt; 3) // 1, 2
        {
            max = r;
            speed = speed % ((max-1)*2); // speed가 클때 굳이 모두 계산할 필요없이 반복되는 부분을 줄인다
            int dist = speed;

            while (true)
            {
                int next =  x + direction[dir].first * dist;
                if (next &gt;= max ) // 움직일 거리가 경계를 넘어가는 경우 dir = 2
                {
                    x = max-1;
                    dist = next - (max-1);
                    dir = 1;
                }
                else if (next &lt; 0 ) // 움직일 거리가 경계를 넘어가는 경우 dir = 1
                {
                    x = 0;
                    dist = -next;
                    dir = 2;
                }
                else
                {
                    break;
                }
            }
            x = (x + direction[dir].first * dist);
        }
        else // 3, 4 
        {
            max = c;
            speed = speed % ((max-1)*2);
            int dist = speed;

            while (true)
            {
                int next =  y + direction[dir].second * dist;
                if (next &gt;= max ) // 움직일 거리가 경계를 넘어가는 경우 dir = 3
                {
                    y = max-1;
                    dist = next - (max-1);
                    dir = 4;
                }
                else if (next &lt; 0 ) // 움직일 거리가 경계를 넘어가는 경우 dir = 4
                {
                    y = 0;
                    dist = -next;
                    dir = 3;
                }
                else
                {
                    break;
                }
            }
            y = (y + direction[dir].second * dist);
        }
    }
};

int min(int a, int b) { return a &lt; b ? a : b; }

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

    cin &gt;&gt; r &gt;&gt; c &gt;&gt; m;
    board.assign(r, vector&lt;Shark*&gt;(c, nullptr));

    for (int i=0; i&lt;m; ++i)
    {
        int x, y, s, d, z;
        cin &gt;&gt; x &gt;&gt; y &gt;&gt; s &gt;&gt; d &gt;&gt; z;
        Shark* sharkPtr = new Shark();
        sharkPtr-&gt;x = x-1;
        sharkPtr-&gt;y = y-1;
        sharkPtr-&gt;speed = s;
        sharkPtr-&gt;dir = d;
        sharkPtr-&gt;size = z;

        sharkPtr-&gt;setShark();
    }

    int cntSize = 0;
    for (int i=0; i&lt;c; ++i)
    {
        // 낚시질
        for (int line = 0; line &lt; r; ++line)
        {
            if (board[line][i] != nullptr)
            {
                cntSize += board[line][i]-&gt;size;
                // cout &lt;&lt; line &lt;&lt; &quot;, &quot; &lt;&lt; i &lt;&lt; &quot;: &quot; &lt;&lt; board[line][i]-&gt;size &lt;&lt; endl;
                board[line][i] = nullptr;
                break;
            }
        }

        // 상어 이동
        vector&lt;Shark*&gt; buffer;
        for (int x=0; x &lt; r; ++x)
        {
            for (int y=0; y&lt;c; ++y)
            {
                if (board[x][y])
                {
                    board[x][y]-&gt;move();
                    buffer.push_back(board[x][y]);
                }
                board[x][y] = nullptr;
            }
        }

        for (auto&amp; shark : buffer)
        {
            shark-&gt;setShark();
        }

    }

    cout &lt;&lt; cntSize &lt;&lt; endl;
    return 0;
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 10775 공항 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-10775-%EA%B3%B5%ED%95%AD-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-10775-%EA%B3%B5%ED%95%AD-C</guid>
            <pubDate>Mon, 04 Sep 2023 14:39:37 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/7d79cc92-4e1c-4649-92b6-e12c595fa4fc/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/10775">10775번: 공항</a></p>
<h1 id="풀이">풀이</h1>
<p>큰 수의 비행기는 작거나 같은 수의 게이트에 도킹이 가능하다.
큰수의 비행기가 작은 수의 게이트에 먼저 도킹을 하게 되면 나중에 작은 수의 비행기가 그 게이트에 도킹을 못하게 되므로 비행기는 가능한 가장 큰 수의 게이트에 도킹해야 한다.</p>
<p>N 비행기가 N 게이트에 도킹을 했다면, 다음 N 비행기는 N-1 게이트에 도킹을 해야한다.
이렇게 이미 도킹되어 1 작은 게이트에 도킹해야 한다면 N과 N-1을 같은 집합으로 묶어 N이든, N-1이든 모두 N-1로 취급하여 처리하면 된다. 이때 Union-Find 알고리즘을 사용한다.</p>
<ul>
<li>도킹할 게이트를 찾기 위해 <code>find(N)</code> 함수를 사용한다.</li>
<li>비행기가 N게이트에 도킹되면 N과 N-1을 같은 집합으로 <code>merge(N, N-1)</code> 한다.<ul>
<li>이때 항상 작은수가 root 가 되도록 하여 <code>find</code> 함수로 찾은 수가 항상 도킹 가능한 게이트가 되도록 한다.</li>
</ul>
</li>
</ul>
<p>만약 N-1 = 0 이라면 더이상 도킹 가능한 게이트가 없으므로 해당 번째를 출력하고 끝내면된다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

vector&lt;int&gt; head;

int find(int x)
{
    if (head[x] == x)
        return x;

    return head[x] = find(head[x]);
}

void merge(int x, int y)
{
    x = find(x);
    y = find(y);

    if (x == y)
        return;

    if (x &gt; y) // 문제의 조건때문에 작은놈이 항상 root 
        head[x] = y;
    else
        head[y] = x;
}

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

    int g, p;
    cin &gt;&gt; g;
    cin &gt;&gt; p;

    head.resize(g+1);
    for (int i=0; i&lt;g+1; ++i)
        head[i] = i;

    int cnt = 0;
    while(p--)
    {

        int gi;
        cin &gt;&gt; gi;

        int ptr = find(gi);
        if (ptr &gt; 0)
        {
            ++cnt;
            merge(ptr, ptr-1);
        }
        else
            break;

    }

    cout &lt;&lt; cnt &lt;&lt; endl;
    return 0;
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 17471 게리맨더링 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-17471-%EA%B2%8C%EB%A6%AC%EB%A7%A8%EB%8D%94%EB%A7%81-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-17471-%EA%B2%8C%EB%A6%AC%EB%A7%A8%EB%8D%94%EB%A7%81-C</guid>
            <pubDate>Fri, 01 Sep 2023 10:32:15 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/69754f1e-9e5c-4a51-94b8-38aba8faec83/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/8dfcf701-1702-4c3e-9bf0-54ebfe74b642/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/17471">17471번: 게리맨더링</a></p>
<h1 id="풀이">풀이</h1>
<p>N의 크기가 최대 10인데도 불구하고 추가시간 없는 0.5초에 쫄아서 완전탐색을 생각하지 못했다. </p>
<p>1 ~ n 까지의 구역을 두 개로 나누기 위해 비트마스킹을 이용해서 완전탐색을 했다.
두 선거구를 나누었을 때 각 선거구의 구역은 서로 이어져 있어야 하므로 그래프 탐색을 했을 때 전부 탐색이 가능해야 한다.
두 선거구를 비트마스킹으로 표시하는 uint32 크기의 <code>red</code> 변수와 각 그래프 탐색 후 방문 여부를 저장하는 <code>visited</code> 를 비교하여 같은 선거구의 각 구역이 연결되어 있는지 확인하였다.</p>
<p>두 선거구 그룹을 서로 그래프 탐색하여 모두 연결되어 있는지 확인하고 연결되어 있다면 그래프 탐색할때 구한 각 선거구의 인구를 비교하여 그 차가 최소가 되는 값을 저장한다.</p>
<p>문제를 풀때 두 선거구를 red 와 blue로 하고 문제를 풀었는데, red에 속한 위치를 비트1로 표현하는 변수 <code>red</code>가 있을 때 이와 반대되는 비트를 가지는 <code>blue</code>를 구하기 위해서는 <code>~( (~0 &lt;&lt; n) ^ red)</code>로 구할 수 있었다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

int n;
vector&lt;int&gt; population;
vector&lt;vector&lt;int&gt;&gt; graph;
unsigned int red = 0;
unsigned int visited = 1;
int answer = INT32_MAX;

int sumVec(vector&lt;int&gt;&amp; input)
{
    int ret = 0;
    for (auto i: input)
        ret += i;
    return ret;
}

int min(int a, int b) { return a &lt; b ? a : b; }
int abs(int a) { return a &lt; 0 ? -a : a; }

int findBlue(int v)
{
    int ret = population[v];
    for (int next : graph[v])
    {
        if (red &amp; 1 &lt;&lt; next)
            continue;
        if (visited &amp; 1 &lt;&lt; next)
            continue;

        visited = visited | 1 &lt;&lt; next;
        ret += findBlue(next);
    }
    return ret;
}

int findRed(int v)
{
    int ret = population[v];
    for (int next : graph[v])
    {
        if (!(red &amp; 1 &lt;&lt; next))
            continue;
        if (visited &amp; 1 &lt;&lt; next)
            continue;

        visited = visited | 1 &lt;&lt; next;
        ret += findRed(next);
    }
    return ret;
}

int main() 
{
    cin &gt;&gt; n;
    population.resize(n); 
    graph.resize(n);

    for (int i=0; i&lt;n; ++i)
        cin &gt;&gt; population[i];

    for (int i=0; i&lt;n; ++i)
    {
        int cnt;
        cin &gt;&gt; cnt;
        while (cnt--)
        {
            int dest;
            cin &gt;&gt; dest;
            graph[i].push_back(dest-1);
        }
    }

    int totalPo = sumVec(population);

    while (red != 1 &lt;&lt; n)
    {
        ++red;
        int redPopulation;
        int bluePopulation;

        // 파란색 시작점 찾기
        int blueStart;
        for (int i=0; i&lt;n; ++i)
        {
            if (red &amp; 1 &lt;&lt; i)
                continue;
            blueStart = i;
            break;
        }
        // 파란색 탐색
        visited = 0 | 1 &lt;&lt; blueStart;
        bluePopulation = findBlue(blueStart);
        if (visited != ~( (~0 &lt;&lt; n) ^ red))
            continue;

        // 빨간색 시작점은 항상 1, 빨간색 탐색
        visited = 1;
        redPopulation = findRed(0);

        if (visited != red)
            continue;

        answer = min(answer, abs(bluePopulation - redPopulation));

    }

    if (answer == INT32_MAX)
        answer = -1;
    cout &lt;&lt; answer &lt;&lt; endl;
    return 0;
}</code></pre>
<p>두 선거구는 구별하지 않기 때문에 두 선거구를 빨간색과 파란색으로 나눈다고 가정하게 되면 1번 지역을 항상 빨간색에 넣어둔다 가정해도 문제되지 않는다. 이 사실을 이용해서 더 빠른 코드를 작성할 수 있지 않을까 생각도 해보았다. $2^n$ 아 아닌 $2^{n-1}$까지 반복하면 되기 때문에</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 16118 달빛 여우 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-16118-%EB%8B%AC%EB%B9%9B-%EC%97%AC%EC%9A%B0-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-16118-%EB%8B%AC%EB%B9%9B-%EC%97%AC%EC%9A%B0-C</guid>
            <pubDate>Fri, 01 Sep 2023 10:02:09 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/57bbe661-568c-4c73-9b82-9da6ce675b77/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/16118">16118번: 달빛 여우</a></p>
<h1 id="풀이">풀이</h1>
<p>늑대놈 때문에 많이 힘들었다.</p>
<p>늑대는 여우보다 2배의 속도, 절반의 속도로 움직인다. 따라서 처음 입력으로 주어지는 그루터기 사이의 거리를 조절하여 늑대의 속도를 조절했다.
거리를 2배로 하여 절반의 속도, 거리를 1/2배 하여 두배의 속도를 표현했다. 하지만 모든 거리가 정수로 표현되는 것이 큰 수를 표현하기에 알맞기 때문에 처음 주어지는 거리에 1배, 2배, 4배를 하여 늑대(두배 속도), 여우, 늑대(절반 속도)를 표현하였다.</p>
<p>또한 늑대는 움직일 때마다 속도가 달라지므로 같은 그루터기에 도착하더라도 해당 그루터기를 두배의 속도로 왔는지, 절반의 속도로 왔는지에 따라 값이 달라진다.
그래서 늑대는 최단 거리도 2개로 구해주어야 한다. 그루터기에 2배의 속도로 들어왔을 때, 절반의 속도로 들어왔을 때 다른 값을 각각 저장해주어야 한다.</p>
<p>다익스트라로 각 노드를 우선순위 큐에 넣을 때 현재 속도(두배인지, 절반인지)에 대한 정보도 포함하여 같이 넣어준다. pop() 할때 그 정보를 토대로 다음 위치까지의 거리를 구하고 해당 최단 경로를 어디에 저장할지 결정한다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;queue&gt;

using namespace std;

struct Node
{
    int to;
    int64_t weight;
    bool isDouble;

    bool operator&gt;(Node input)
    {
        return this-&gt;weight &gt; input.weight;
    }
};

template &lt;typename T&gt;
struct cmp
{
    bool operator()(T a, T b)
    {
        return a &gt; b;
    }
};

int n, m;
vector&lt;vector&lt;Node&gt;&gt; graph[3];

int64_t min(int64_t a, int64_t b)
{
    return a &lt; b ? a : b;
}

vector&lt;int64_t&gt; dijkstra(int start)
{
    priority_queue&lt;Node, vector&lt;Node&gt;, cmp&lt;Node&gt;&gt; pq;
    vector&lt;int64_t&gt; dist(n+1, INT64_MAX);
    pq.push({start, 0});
    dist[start] = 0;

    while (!pq.empty())
    {
        int cur = pq.top().to;
        int64_t curWeight = pq.top().weight;
        pq.pop();

        if (curWeight &gt; dist[cur])
            continue;

        for (auto n : graph[1][cur])
        {
            int next = n.to;
            int64_t nextWeight = curWeight + n.weight;

            if (nextWeight &gt;= dist[next])
                continue;

            dist[next] = nextWeight;
            pq.push({next, nextWeight});
        }
    }

    return dist;
}

vector&lt;vector&lt;int64_t&gt;&gt; dijkstra2(int start)
{
    priority_queue&lt;Node, vector&lt;Node&gt;, cmp&lt;Node&gt;&gt; pq;
    vector&lt;vector&lt;int64_t&gt;&gt; dist(2);
    dist[0] = vector&lt;int64_t&gt;(n+1, INT64_MAX);
    dist[1] = vector&lt;int64_t&gt;(n+1, INT64_MAX);
    pq.push({start, 0, true});
    dist[true][1] = 0;

    while (!pq.empty())
    {
        int cur = pq.top().to;
        int64_t curWeight = pq.top().weight;
        bool curIsDouble = pq.top().isDouble;
        pq.pop();

        if (curWeight &gt; dist[curIsDouble][cur])
            continue;

        for (auto n : graph[!curIsDouble * 2][cur])
        {
            int next = n.to;
            int64_t nextWeight = curWeight + n.weight;

            if (nextWeight &gt;= dist[!curIsDouble][next])
                continue;

            dist[!curIsDouble][next] = nextWeight;
            pq.push({next, nextWeight, !curIsDouble});
        }
    }

    return dist;
}

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

    cin &gt;&gt; n &gt;&gt; m;
    for (int i=0; i&lt;3; ++i)
        graph[i].assign(n+1, vector&lt;Node&gt;());

    while (m--)
    {
        int a, b;
        int64_t weight;
        cin &gt;&gt; a &gt;&gt; b &gt;&gt; weight;
        for (int i=0; i&lt;3; ++i)
        {
            graph[i][a].push_back({b, weight * 1 &lt;&lt; i});
            graph[i][b].push_back({a, weight * 1 &lt;&lt; i});
        }
    }

    vector&lt;int64_t&gt; foxDist = dijkstra(1);
    vector&lt;vector&lt;int64_t&gt;&gt; wolfDist = dijkstra2(1);

    int cnt = 0;
    for (int i=1; i&lt;n+1; ++i)
    {
        if (min(wolfDist[0][i], wolfDist[1][i]) &gt; foxDist[i])
        {
            ++cnt;
        }
    }

    cout &lt;&lt; cnt &lt;&lt; endl;
    return 0;
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 10711 모래성 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-10711-%EB%AA%A8%EB%9E%98%EC%84%B1-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-10711-%EB%AA%A8%EB%9E%98%EC%84%B1-C</guid>
            <pubDate>Fri, 01 Sep 2023 09:33:08 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/6607eea8-a30a-469b-89fc-2586f9751110/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/10711">10711번: 모래성</a></p>
<h1 id="풀이">풀이</h1>
<p>처음엔 완전탐색으로 해결해보려 했다. 파도가 칠때마다 모든 모래성의 튼튼함 정도와 주변 모래성의 개수를 확인해서 해당 모래성이 무너질지 아닐지를 판단했는데, 당연하게도 시간초과가 발생했다.</p>
<p>좀 더 빠른 방법을 위해 파도가 칠때마다 모든 모래성을 판단하는것이 아닌, 파도가 쳤을 때 무너진 모래성 주변만을 탐색해서 판단하기로 했다.</p>
<p>모래성이 없는 위치를 전부 큐에 넣고 bfs로 탐색하며 해당 위치에 영향을 맏는 모래성의 튼튼함 정도를 1씩 깎았다. 모래성의 튼튼함 정도가 0이 될 경우 buffer에 임시로 저장해두고 다음 파도가 칠때 다른 bfs 탐색을 시작하기 전에 큐에 buffer에 있던 위치들을 넣는다. 이미 무너져서 튼튼함 정도가 0인 모래성들과의 중복을 피할 수 있도록 주의한다.
buffer의 크기가 0이 될 때까지 반복하여 몇번의 bfs 탐색을 했는지 출력한다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;queue&gt;

using namespace std;

int w, h;
vector&lt;vector&lt;int&gt;&gt; sandCastle;
vector&lt;pair&lt;int, int&gt;&gt; buffer;
vector&lt;pair&lt;int, int&gt;&gt; dir { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };
int cnt = 0;

bool OOB(int x, int y)
{
    return x &lt; 0 || x &gt;= h || y &lt; 0 || y &gt;= w;
}

void bfs()
{
    queue&lt;pair&lt;int, int&gt;&gt; q;
    for (auto i : buffer)
        q.push(i);

    buffer.clear();

    while(!q.empty())
    {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();

        for (auto d : dir)
        {
            int nx = d.first + x;
            int ny = d.second + y;

            if (OOB(nx, ny))
                continue;

            --sandCastle[nx][ny];
            if (sandCastle[nx][ny] == 0)
                buffer.push_back({nx, ny});

        }
    }
}

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

    cin &gt;&gt; h &gt;&gt; w;
    sandCastle.resize(h);
    for (int i=0; i&lt;h; ++i)
    {
        sandCastle[i].reserve(w);
        string input;
        cin &gt;&gt; input;
        for (auto c : input)
        {
            if (c == &#39;.&#39;)
                sandCastle[i].push_back(0);
            else
                sandCastle[i].push_back(c - &#39;0&#39;);
        }
    }

    for (int i=0; i &lt; h; ++i)
    {
        for (int j=0; j &lt;w; ++j)
        {
            if (sandCastle[i][j] == 0)
                buffer.push_back({i, j});
        }
    }

    while (true)
    {
        bfs();
        if (buffer.size() == 0)
            break;
        ++cnt;
    }

    cout &lt;&lt; cnt &lt;&lt; endl;

    return 0;
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 2211 네트워크 복구 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-2211-%EB%84%A4%ED%8A%B8%EC%9B%8C%ED%81%AC-%EB%B3%B5%EA%B5%AC-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-2211-%EB%84%A4%ED%8A%B8%EC%9B%8C%ED%81%AC-%EB%B3%B5%EA%B5%AC-C</guid>
            <pubDate>Fri, 01 Sep 2023 09:15:26 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/fca11fab-46c1-4bc6-bbc1-2b231ff31ff4/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/2211">2211번: 네트워크 복수</a></p>
<h1 id="풀이">풀이</h1>
<p>최소 스패닝 트리를 구하는 것인지, 다익스트라 최단 경로를 구하는 것인지 헷갈렷지만 
<em>슈퍼컴퓨터가 다른 컴퓨터들과 통신하는데 걸리는 최소 시간이, 원래의 네트워크에서 통신하는데 걸리는 최소 시간보다 커져서는 안 된다.</em> 라는 조건 때문에 다익스트라 최단경로를 구하는 것을 알았다.
슈퍼 컴퓨터에서 다른 모든 컴퓨터까지의 최단 경로를 구해야 한다.</p>
<p>다익스트라 알고리즘은 최단 경로까지의 거리를 구하는 알고리즘이라 경로를 구하기 위해서는 별도의 작업이 필요하다.
다익스트라로 찾아낸 경로는 결국 출발지점을 루트로 하는 트리이다. 따라서 최단 경로를 찾을 때마다 각 노드간의 부모-자식 관계를 저장하여 경로를 알아낼 수 있다.</p>
<p>또한 트리이므로 N개의 노드가 있을 때 간선의 개수는 항상 N-1 이다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;queue&gt;
#include &lt;set&gt;

using namespace std;

int n, m;
vector&lt;vector&lt;struct Edge&gt;&gt; graph;
vector&lt;int&gt; parent;

struct Edge
{
    int dest;
    int cost;

    bool operator&gt;(Edge input)
    {
        return this-&gt;cost &gt; input.cost;
    }
};

struct cmp
{
    bool operator()(int a, int b){
        return a &gt; b;
    }
    bool operator()(Edge a, Edge b)
    {
        return a &gt; b;
    }
};

void dijkstra(int start)
{
    priority_queue&lt;Edge, vector&lt;Edge&gt;, cmp&gt; pq;
    vector&lt;int&gt; dist(n+1, 10*(n-1) + 1); // 최대값 맞는지 잘 모르겟음..
    pq.push({1, 0});
    dist[1] = 0;

    while (!pq.empty())
    {
        int cur = pq.top().dest;
        int curCost = pq.top().cost;
        pq.pop();

        if (dist[cur] &lt; curCost)
            continue;

        for (auto n : graph[cur])
        {
            int next = n.dest;
            int nextCost = curCost + n.cost;

            if (nextCost &gt;= dist[next]) // 비용이 더 적을때만 갱신
                continue;

            dist[next] = nextCost;
            pq.push({next, nextCost});

            parent[next] = cur;
        }
    }

}

int main() 
{
    cin.tie(0);
    ios_base::sync_with_stdio(false);
    cin &gt;&gt; n &gt;&gt; m;
    graph.assign(n+1, vector&lt;Edge&gt;());
    parent.assign(n+1, 0);
    for (int i=0; i&lt;m; ++i)
    {
        int a, b, c;
        cin &gt;&gt; a &gt;&gt; b &gt;&gt; c;
        graph[a].push_back({b, c});
        graph[b].push_back({a, c});
    }

    dijkstra(1);

    cout &lt;&lt; n-1 &lt;&lt; &quot;\n&quot;;
    for (int i=2; i&lt;n+1; ++i)
    {
        cout &lt;&lt; i &lt;&lt; &quot; &quot; &lt;&lt; parent[i] &lt;&lt; &quot;\n&quot;;
    }

    return 0;
}</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[[백준] 9370 미확인 도착지 (C++)]]></title>
            <link>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-9370-%EB%AF%B8%ED%99%95%EC%9D%B8-%EB%8F%84%EC%B0%A9%EC%A7%80-C</link>
            <guid>https://velog.io/@i_am_gr00t/%EB%B0%B1%EC%A4%80-9370-%EB%AF%B8%ED%99%95%EC%9D%B8-%EB%8F%84%EC%B0%A9%EC%A7%80-C</guid>
            <pubDate>Wed, 23 Aug 2023 06:17:19 GMT</pubDate>
            <description><![CDATA[<h1 id="문제">문제</h1>
<p><img src="https://velog.velcdn.com/images/i_am_gr00t/post/e78b6086-9e4d-4c86-aa89-500dfd4f487b/image.png" alt=""></p>
<p><a href="https://www.acmicpc.net/problem/9370">9370번: 미확인 도착지</a></p>
<h1 id="풀이">풀이</h1>
<p>s 부터 시작해서 목적지 후보로의 최단 거리를 구하는 문제이다. 이때 그 최단 거리 중 입력으로 주어지는 g, h 사이의 도로를 반드시 지나는 목적지 후보들을 출력하는 문제가 된다.</p>
<p>출발지점이 하나 주어지고 그에 대한 최단 거리를 구해야 하므로 다익스트라 알고리즘을 사용했다.
하지만 다익스트라는 해당 노드까지의 경로가 아닌 거리만을 구하는 알고리즘이라 한번에 뚝딱 정답이 나오지 않았다.</p>
<p>g, h사이의 도로를 반드시 지나는 최단 경로라면
<code>출발지점(s)</code> -&gt; ... -&gt; <code>g</code>혹은 <code>h</code> -&gt; <code>h</code>혹은 <code>g</code> -&gt; ... -&gt; <code>도착지점</code> 이다.
그렇다면 <code>s</code> 부터 <code>hg</code>도로를 지났을 때의 최단거리 + <code>hg</code>도로를 지난 후 도착지점 까지의 최단 거리가 <code>s</code>부터 도착지점까지의 최단거리가 같아야 한다.</p>
<p>만약 어떤 목적지 후보까지의 최단 거리가 hg 도로를 포함하지 않는다면 <strong><em><code>s</code> 부터 <code>hg</code>도로를 지났을 때의 최단거리 + <code>hg</code>도로를 지난 후 도착지점 까지의 최단 거리</em></strong>가 다익스트라로 구한 목적지 후보까지의 최단거리보다 큰 값을 가지게 될 것이다.</p>
<h1 id="코드">코드</h1>
<pre><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;queue&gt;
#include &lt;algorithm&gt;

#define node second
#define weight first

using namespace std;

int n, m, t;
int s, g, h;
vector&lt;vector&lt;pair&lt;int, int&gt;&gt;&gt; edges;
vector&lt;int&gt; destination;

vector&lt;int&gt; dijkstra(int start)
{
    vector&lt;int&gt; dist(n+1, INT32_MAX);

    priority_queue&lt;pair&lt;int, int&gt;&gt; pq;
    pq.push({0, start});
    dist[start] = 0;

    while(!pq.empty())
    {
        auto cur = pq.top();
        pq.pop();

        if (dist[cur.node] &lt; -cur.weight)
            continue;

        for (auto e : edges[cur.node])
        {    
            int nextNode = e.node;
            int nextWeight = e.weight + dist[cur.node];    

            if (dist[nextNode] &lt;= nextWeight)
                continue;

            dist[nextNode] = nextWeight;
            pq.push({-nextWeight, nextNode});
        }
    }

    return dist;
}

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

    int testCase;
    cin &gt;&gt; testCase;
    while (testCase--)
    {
        cin &gt;&gt; n &gt;&gt; m &gt;&gt; t;
        cin &gt;&gt; s &gt;&gt; g &gt;&gt; h;
        edges.assign(n+1, vector&lt;pair&lt;int, int&gt;&gt;());
        for (int i=0; i&lt;m; ++i)
        {
            int a, b, dist;
            cin &gt;&gt; a &gt;&gt; b &gt;&gt; dist;
            edges[a].emplace_back(dist, b);
            edges[b].push_back({dist, a});
        }
        for (int i=0; i&lt;t; ++i)
        {
            int d;
            cin &gt;&gt; d;
            destination.push_back(d);
        }

        vector&lt;int&gt; init = dijkstra(s);
        vector&lt;int&gt; distG = dijkstra(g);
        vector&lt;int&gt; distH = dijkstra(h);

        vector&lt;int&gt; answer;
        int offset = init[g] &gt; init[h] ? init[g] : init[h];
        vector&lt;int&gt; compare = init[g] &gt; init[h] ? distG : distH;
        for (auto d : destination)
        {
            if (init[d] == compare[d] + offset)
                answer.push_back(d);
        }

        sort(answer.begin(), answer.end());
        for (auto a : answer)
            cout &lt;&lt; a &lt;&lt; &quot; &quot;;
        cout &lt;&lt; endl;

        destination.clear();
        edges.clear();
    }


    return 0;
}</code></pre>
]]></description>
        </item>
    </channel>
</rss>