<?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>Algorithms &#8211; WONIZZ.LOG</title>
	<atom:link href="https://blog.wonizz.com/category/tech/algorithms/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.wonizz.com</link>
	<description>AI 자동화를 직접 굴려 본 개발자의 실무 교훈</description>
	<lastBuildDate>Fri, 21 Aug 2026 15:45:27 +0000</lastBuildDate>
	<language>ko-KR</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0.2</generator>

<image>
	<url>https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/08/wz-siteicon-512.png?fit=32%2C32&#038;ssl=1</url>
	<title>Algorithms &#8211; WONIZZ.LOG</title>
	<link>https://blog.wonizz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">152411368</site>	<item>
		<title>[Algorithms] 투 포인터 알고리즘</title>
		<link>https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/</link>
					<comments>https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Fri, 29 Jan 2021 10:35:52 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1657</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 투 포인터 알고리즘에 대해서 정리를 해보도록 하겠습니다. 필자가 생각하기에는 특정 알고리즘의 영역이라기보다는 기법중 하나로 생각이 됩니다. 문제 유형으로는 1차원 배열에서 합이 특정 값이 되는 부분 배열이 몇개가 되는지를 구하는 내용이 많습니다. 이번 포스팅은 특정 알고리즘이 아니므로, 예시 문제를 먼저 정리하고 관련해서 투포인터 기법을 적용하여 풀이를 하는 내용에 대해서 정리하겠습니다. 1.&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/">[Algorithms] 투 포인터 알고리즘</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 투 포인터 알고리즘에 대해서 정리를 해보도록 하겠습니다. 필자가 생각하기에는 특정 알고리즘의 영역이라기보다는 기법중 하나로 생각이 됩니다.

문제 유형으로는 1차원 배열에서 합이 특정 값이 되는 부분 배열이 몇개가 되는지를 구하는 내용이 많습니다.

이번 포스팅은 특정 알고리즘이 아니므로, 예시 문제를 먼저 정리하고 관련해서 투포인터 기법을 적용하여 풀이를 하는 내용에 대해서 정리하겠습니다.

<h2>1. 문제 설명</h2>

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/2003" target="_blank" rel="noopener">수열의 합2</a>

<hr/>

N개의 수로 된 수열 A[1], A[2], …, A[N] 이 있다. 이 수열의 i번째 수부터 j번째 수까지의 합 A[i] + A[i+1] + … + A[j-1] + A[j]가 M이 되는 경우의 수를 구하는 프로그램을 작성하시오.

<pre><code class="line-numbers">10 5
1 2 3 4 2 5 3 1 1 2
</code></pre>

예시는 위와 같습니다. 총 10개의 input이 있고, 값의 합이 5만큼 되는 연속되는 부분 수열을 찾는 것입니다.

예를들어, {2, 3}의 합이 총 5가 되므로 답중 하나의 예시가 됩니다.

<h2>2. 투 포인터 기법 적용</h2>

만약, 전체 해답을 모두 구한다면, 2중 for문을 돌려서 해결 할 수 있습니다. 모든 경우의 수를 봤을 때, O(N^2)만큼의 시간 복잡도가 걸리므로, 조건에서 fail이 되게 됩니다.

따라서, 위와 같은 문제는 특정 기법을 적용해야 되는데 여기서 사용되는 것이 바로 투포인터 기법입니다.

start, end이렇게 2개의 포인터를 준비합니다. 그리고 다음과 같은 알고리즘 순서로 진행을 합니다.

<ul>
<li>end 포인터가 계속 늘려가면서 합의 값이 M이거나 보다 크게 되는 구간까지 늘립니다.</li>
<li>구간합이 M보다 작아지는 지점까지 start 포인터를 늘려 갑니다.</li>
<li>합의 구간이 M이 되는 경우 result값을 한개씩 증가합니다.</li>
</ul>

2개의 포인터가 동시에 움직이면서, 전체 가지 수중에서 불필요한 검증을 제거 하기위해서 최적의 해만을 찾아나가는 기법입니다.

<h2>3. 투 포인터 그림 설명</h2>

위의 예시에 대해서 애니메이션으로 보시면 확실히 이해가 되실 것입니다. 아래의 그림이미지를 보면서 하나씩 정리해보겠습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/twopoint_1.png?w=1200&#038;ssl=1" alt="twopointer_1" />

처음에는 위에 보이는것과 같이, start/end 포인터가 0지점을 가리키고 있습니다. 그리고 현재의 SUM값은 0 입니다.

end포인터를 우측으로 옮기면서 값을 하나씩 더해나갑니다. 구간합이 M(위의 예시에서는 5)과 같거나 커지는 지점까지 늘려나갑니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/twopoint_4.png?w=1200&#038;ssl=1" alt="twopointer_4" />

그리고 위의 그림과 같이 M값을 넘어가게 되면, start 포인터를 오른쪽으로 옮기면서 SUM값을 빼게 됩니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/twopoint_5.png?w=1200&#038;ssl=1" alt="twopointer_5" />

위의 그림과 같이 합이 M이 되는 구간을 찾고 result에 값을 한개 더하게 됩니다. 그리고 M과 같거나 커졌기 때문에 다시 start 포인터를 우측으로 옮깁니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/twopoint_6.png?w=1200&#038;ssl=1" alt="twopointer_6" />

위와 같은 방식으로 계속해서 start/end 2개의 포인터를 움직이면서 구간합이 M이 되는 것을 찾고 result를 추가해줍니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/twopoint_12.png?w=1200&#038;ssl=1" alt="twopointer_12" />

2번째 해답은 위와같습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/twopoint_14.png?w=1200&#038;ssl=1" alt="twopointer_14" />

3번째 해답은 위와같습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/twopoint_15.png?w=1200&#038;ssl=1" alt="twopointer_15" />

다시 start/end 포인터를 하나씩 옮기게 되면 위와 같고, end포인터는 끝까지 갔습니다. 더이상의 해답이 없기 때문에 start 포인터도 끝까지 우측으로 옮기게 되고, 해답을 찾습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/twopoint_16.png?w=1200&#038;ssl=1" alt="twopointer_16" />

최종적으로는 답이 3개가 되고 while 문은 끝이 납니다.

<h2>4. 소스 코드</h2>

<pre><code class="language-java line-numbers">import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    static int N,K;
    static int[] Arr;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine().trim());
        N = Integer.parseInt(st.nextToken());
        K = Integer.parseInt(st.nextToken());
        Arr = new int[N + 1];
        st = new StringTokenizer(br.readLine().trim());
        for (int i = 0; i < N; i++) {
            Arr[i] = Integer.parseInt(st.nextToken());
        }

        int i,j;
        i = 0 ; j = 0;
        int sum = 0;
        int count = 0;
        while(true){
            if(sum >= K) sum -= Arr[i++];
            else if(j == N) break;
            else sum += Arr[j++];
            if(sum == K) count++;
        }
        System.out.println(count);
    }
}
</code></pre>

위의 소스코드는 모든 내용을 기입하였고, 그 내용중에서 투포인터가 적용되는 부분은 아래와 같습니다.

<pre><code class="language-java line-numbers">while(true){
    if(sum >= K) sum -= Arr[i++];
    else if(j == N) break;
    else sum += Arr[j++];
    if(sum == K) count++;
}
</code></pre>

while문이 계속해서 수행되면서, 아래의 if문을 보게 되면, j포인터가 end포인터고, i포인터가 start포인터가 되면서 수행하게 됩니다.

<h2>5. 마치며&#8230;</h2>

이번시간에는 투포인터 기법에 대해서 정리를 해보았습니다. 알고리즘을 학습하면서 정말 하나의 문제를 풀더라도 다양한 기법과 알고리즘이 존재한다는 것을 알게 되었습니다. 관련한 알고리즈 문제는 추후에 포스팅 하도록 하겠습니다. 투포인터 문제는 1차원 배열이 존재하고 특정값으로 매칭되는 부분 수열을 구하는 문제에서 적용해 볼 수 있다는 것을 알게 되었습니다.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/">[Algorithms] 위상 정렬 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/">[Algorithms] BFS, DFS 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/14/algorithms-lca/">[Algorithms] LCA 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/03/bellman-ford/">[Algorithms] 벨만-포드 알고리즘</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/">[Algorithms] 투 포인터 알고리즘</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1657</post-id>	</item>
		<item>
		<title>[Algorithms] 위상 정렬 알고리즘</title>
		<link>https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/</link>
					<comments>https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Wed, 20 Jan 2021 00:08:26 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1647</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 위상정렬 알고리즘에 대해서 정리를 해보도록 하겠습니다. 위상 정렬 알고리즘은 순서가 정해져있는 작업을 차례대로 수행해야 할 때 그 순서를 결정해 주기 위한 알고리즘입니다. 예를들어, 회사에 입사해서 주재원가기까지의 과정이 아래의 이미지에 담겨있다고 가정하겠습니다. 방향성이 있는 그래프이고, 어떤 행위를 수행하기 위해서는 사전 조건으로 반드시 수행되어야 될 임무가 있습니다. 즉, 순서가 정해져 있어야 합니다.&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/">[Algorithms] 위상 정렬 알고리즘</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 위상정렬 알고리즘에 대해서 정리를 해보도록 하겠습니다.  위상 정렬 알고리즘은 순서가 정해져있는 작업을 차례대로 수행해야 할 때 그 순서를 결정해 주기 위한 알고리즘입니다.

예를들어, 회사에 입사해서 주재원가기까지의 과정이 아래의 이미지에 담겨있다고 가정하겠습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%9C%84%EC%83%81%EC%A0%95%EB%A0%AC_1.png?w=1200&#038;ssl=1" alt="위상정렬_1" />

방향성이 있는 그래프이고, 어떤 행위를 수행하기 위해서는 사전 조건으로 반드시 수행되어야 될 임무가 있습니다. 즉, 순서가 정해져 있어야 합니다. 회사 사이트에 가입을 하기 위해서는 사전에 회사에 입사를 해야된다는 조건이 있습니다.

위상 정렬의 흐름으로 나열을 하면 다음과 같습니다.

회사 입사 -> 정직원 되기 -> 회사 사이트 가입하기 -> SW 검정 취득 -> 대학원 서류 작성 -> 대학원 진학 -> 주재원

위와 같이 정렬을 하면, 주재원가기 까지 순서를 이어나갈 수 있습니다. 위상 정렬이 적용되기 위해서는 DAG(Directed Acyclic Grapth)에만 적용이 가능합니다. 싸이클이 발생하면 순서상으로 어디가 더 선행이 되어야 하는지를 정할 수 없기 때문에 싸이클이 생겨서는 안됩니다.

<h2>1. 위상 정렬 알고리즘 동작 방식</h2>

필자 같은 경우는, 위상정렬을 구현할 때 BFS 방식을 이용해서 구현을 했습니다. 구현을 하기위해서는 각 노드를 target으로 하는 정점의 갯수가 몇개인지를 파악 해야됩니다. 가령 1->2 와 같은 간선이 있으면, 2번 정점 입장에서는 1번으로부터 들어오는 간선 정보 +1이 생기는 것입니다.

이런식의 간선정보를 input정보로부터 받아서 업데이트를 해야됩니다.

<ul>
<li>linecount : 1차원 배열로 해당 정점을 target으로 하는 간선이 몇개인지를 표기하는 변수입니다.</li>
<li>result : 1차원 배열로 linecount를 하나씩 지워주면서 0이 되는 시점에 해당 변수에 담아 줍니다. 즉, 위상의 순서에 대한 결과입니다.</li>
</ul>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%9C%84%EC%83%81%EC%A0%95%EB%A0%AC_2.png?w=1200&#038;ssl=1" alt="위상정렬_2" />

처음에는 위에서 보이는것과 같이 linecount를 1차원배열로 해서 input정보를 받아줍니다. 최초 시작점은 linecount가 0인 점점이 최상위 위상으로부터 시작이 됩니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%9C%84%EC%83%81%EC%A0%95%EB%A0%AC_3.png?w=1200&#038;ssl=1" alt="위상정렬_3" />

BFS에 의해서 queue에다가 1번 점점을 담았다가 빼면서 연결된 인접리스트에서 7,3을 타겟으로 하고있다는것을 알고 linecount에서 -1을 해줍니다. 위의 그림과 같이 기존에 7,3을 target으로 하는 간선정보는 1개 밖에 없기 때문에 지워주면 0이 되면서, result에 담아줍니다. 여기까지는 1->7->3의 위상이 생기는 것입니다.

그런데, 위상정렬의 특징중 하나가 답이 무조건 1개가 될 수 없다는 것입니다. 인접리스트에 담긴 순서에 따라서, 1->7->3이 될수도있고, 1->3->7이 될수도 있습니다. 즉, 위상정렬에 대한 답은 여러개가 될 수 있다는 특징이 있습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%9C%84%EC%83%81%EC%A0%95%EB%A0%AC_4.png?w=1200&#038;ssl=1" alt="위상정렬_4" />

7,3이 현재 queue에 담겨있고, 위의 그림에서는 3을 먼저 꺼내서 다음 노드인 5에 대한 linecount를 지웠지만, 5같은 경우는 2개의 간선정보가 있었기에 0이 되지 않습니다. 그래서 아직은 result에 들어갈 수가 없는 상태입니다.

7노드를 꺼내서 다음 노드인 2정점을 간후, 간선정보를 지웠더니, 0으로 바뀌었습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%9C%84%EC%83%81%EC%A0%95%EB%A0%AC_5.png?w=1200&#038;ssl=1" alt="위상정렬_5" />

다시 2번 노드가 queue에 들어와있고, 꺼내서 다음 노드인 4에 대한 간선정보를 지워줍니다. 이런식으로 순차적으로 내려가면 다음과 같습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%9C%84%EC%83%81%EC%A0%95%EB%A0%AC_6.png?w=1200&#038;ssl=1" alt="위상정렬_6" />

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%9C%84%EC%83%81%EC%A0%95%EB%A0%AC_7.png?w=1200&#038;ssl=1" alt="위상정렬_7" />

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%9C%84%EC%83%81%EC%A0%95%EB%A0%AC_8.png?w=1200&#038;ssl=1" alt="위상정렬_8" />

<h2>2. 위상 정렬 알고리즘 소스코드</h2>

BFS방식으로 큐를 이용하여 풀이하였습니다.

<h2>3. 관련 알고리즘 문제</h2>

<h2>4. 마치며&#8230;</h2>

<h2>5. 참고</h2>

<a class="wp-editor-md-post-content-link" href="https://gmlwjd9405.github.io/2018/08/27/algorithm-topological-sort.html" target="_blank" rel="noopener">위상정렬 이란?</a>

<a class="wp-editor-md-post-content-link" href="https://m.blog.naver.com/ndb796/221236874984" target="_blank" rel="noopener">위상 정렬</a>
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/">[Algorithms] 투 포인터 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/">[Algorithms] BFS, DFS 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/14/algorithms-lca/">[Algorithms] LCA 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/03/bellman-ford/">[Algorithms] 벨만-포드 알고리즘</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/">[Algorithms] 위상 정렬 알고리즘</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1647</post-id>	</item>
		<item>
		<title>[문제풀이] 사탕 상자</title>
		<link>https://blog.wonizz.com/2021/01/11/acmicpc-2243/</link>
					<comments>https://blog.wonizz.com/2021/01/11/acmicpc-2243/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 11 Jan 2021 02:32:19 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1630</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>1. 설명 사탕 상자 문제 수정이는 어린 동생을 달래기 위해서 사탕을 사용한다. 수정이는 평소에 여러 개의 사탕을 사서 사탕상자에 넣어두고, 동생이 말을 잘 들을 때면 그 안에서 사탕을 꺼내서 주곤 한다. 각각의 사탕은 그 맛의 좋고 나쁨이 1부터 1,000,000까지의 정수로 구분된다. 1이 가장 맛있는 사탕을 의미하며, 1,000,000은 가장 맛없는 사탕을 의미한다. 수정이는 동생이 말을 잘&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2021/01/11/acmicpc-2243/">[문제풀이] 사탕 상자</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<h2>1. 설명</h2>

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/2243" target="_blank" rel="noopener">사탕 상자</a>

<h3>문제</h3>

<hr/>

수정이는 어린 동생을 달래기 위해서 사탕을 사용한다. 수정이는 평소에 여러 개의 사탕을 사서 사탕상자에 넣어두고, 동생이 말을 잘 들을 때면 그 안에서 사탕을 꺼내서 주곤 한다.

각각의 사탕은 그 맛의 좋고 나쁨이 1부터 1,000,000까지의 정수로 구분된다. 1이 가장 맛있는 사탕을 의미하며, 1,000,000은 가장 맛없는 사탕을 의미한다. 수정이는 동생이 말을 잘 들은 정도에 따라서, 사탕상자 안에 있는 사탕들 중 몇 번째로 맛있는 사탕을 꺼내주곤 한다. 예를 들어 말을 매우 잘 들었을 때에는 사탕상자에서 가장 맛있는 사탕을 꺼내주고, 말을 조금 잘 들었을 때에는 사탕상자에서 여섯 번째로 맛있는 사탕을 꺼내주는 식이다.

수정이가 보관하고 있는 사탕은 매우 많기 때문에 매번 사탕상자를 뒤져서 꺼낼 사탕을 골라내는 일은 매우 어렵다. 수정이를 도와주는 프로그램을 작성하시오.

<h3>입력</h3>

<hr/>

첫째 줄에 수정이가 사탕상자에 손을 댄 횟수 n(1≤n≤100,000)이 주어진다. 다음 n개의 줄에는 두 정수 A, B, 혹은 세 정수 A, B, C가 주어진다. A가 1인 경우는 사탕상자에서 사탕을 꺼내는 경우이다. 이때에는 한 정수만 주어지며, B는 꺼낼 사탕의 순위를 의미한다. 이 경우 사탕상자에서 한 개의 사탕이 꺼내지게 된다. 또, A가 2인 경우는 사탕을 넣는 경우이다. 이때에는 두 정수가 주어지는데, B는 넣을 사탕의 맛을 나타내는 정수이고 C는 그러한 사탕의 개수이다. C가 양수일 경우에는 사탕을 넣는 경우이고, 음수일 경우에는 빼는 경우이다. 맨 처음에는 빈 사탕상자에서 시작한다고 가정하며, 사탕의 총 개수는 2,000,000,000을 넘지 않는다. 또한 없는 사탕을 꺼내는 경우와 같은 잘못된 입력은 주어지지 않는다.

<h3>출력</h3>

<hr/>

A가 1인 모든 입력에 대해서, 꺼낼 사탕의 맛의 번호를 출력한다. 물론, A=2 이면서 C&lt;0 일 때는 출력하지 않는다.

<h3>입력예제</h3>

<hr/>

<pre><code class="line-numbers">6
2 1 2
2 3 3
1 2
1 2
2 1 -1
1 2
</code></pre>

<h3>출력예제</h3>

<hr/>

<pre><code class="line-numbers">1
3
3
</code></pre>

<h2> </h2>

<h2>2. 문제풀이</h2>

처음에 이문제를 봤을 때, 세그먼트 트리로 어떻게 풀어야 할지 막막했습니다. 그런데, 생각해보면, 세그먼트 트리에 사탕의 갯수에 맞춰서 트리를 구성합니다. 상위부터 계속해서 체크를 하면서 K번재의 갯수가 있으면, 그만큼 빼주고, 다시 우측으로 가서 K-tree[node]만큼을 계산해서 몇번째인지를 찾게 됩니다.

그림으로 설명을 드리겠습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%84%B8%EA%B7%B8%EB%A8%BC%ED%8A%B8%EB%AC%B8%EC%A0%9C_1.png?w=1200&#038;ssl=1" alt="세그먼트문제_1" />

위의 예에서 3번째의 숫자를 찾는다고 가정을 해봅시다. 루트노드부터 훑어서 내려오게 됩니다.

<pre><code class="language-java line-numbers">public static long query(int node, int start, int end, int k){
        if(start == end){
            System.out.println(start + " ");
            return start;
        }
        if(node *2 <= tree_size &#038;&#038; tree[node * 2] >= k){
            return ret = query(node *2, start, (start + end) / 2, k);
        }
        k -= tree[node * 2];
        if(node * 2 + 1 <= tree_size &#038;&#038; tree[node * 2 + 1] >= k){
            return ret = query(node * 2 + 1, (start + end) / 2 + 1, end, k);
        }
        return 0;
    }
</code></pre>

위의 코드에서 보면, 재귀 형식으로 짜여져 있습니다. 이전의 세그먼트 트리에서의 구조와 유사합니다. 하지만, child node로 내려가는 조건이 tree[node * 2]와 같이 특정 값이 인풋으로 온 k보다 크거나 같을때 내려가도록 되어있습니다.

위의 예시에서는 3번째인 수를 찾을때는 루트 노드(4) >= 3번째가 성립하기 때문에, 아래의 Child Node로 내려가게 됩니다. 그리고 재귀형식으로 범위를 좁혀가면서 호출을 하게 되는 구조입니다.

그러다가 좌측보다 K번째가 큰 경우가 생기게 되면 다음이 수행됩니다.

<pre><code class="language-java line-numbers">k -= tree[node * 2];
</code></pre>

k &#8211; tree[node * 2]를 k로 업데이트를 해줍니다. 위의 예에서는 좌측의 child node(2)와 k번쨰(3)를 보게 되면 k가 크기 때문에 2를 빼준 1을 오른쪽 노드에서 찾게 됩니다.

<pre><code class="language-java line-numbers">if(node * 2 + 1 <= tree_size &#038;&#038; tree[node * 2 + 1] >= k){
    return ret = query(node * 2 + 1, (start + end) / 2 + 1, end, k);
}
</code></pre>

오른쪽 노드도 역시 tree[node * 2 +1]값이 k번째보다 큰지 체크를 하고 같은 방식으로 아래로 내려가게 됩니다.

<pre><code class="language-java line-numbers">if(start == end){
    System.out.println(start + " ");
    return start;
}
</code></pre>

끝으로, 말단 노드(Leaf)까지 내려오게 되면, 해당 index값을 return해주게 됨으로써 k번째 수의 위치를 반환하게 됩니다.

이후에는 반환된 노드에 대해서 -1로 업데이트를 수행하게 됩니다. 이부분이 사탕을 뺴어주는 내용입니다.

<h3>풀이</h3>

<hr/>

<pre><code class="language-java line-numbers">import java.io.*;
import java.util.StringTokenizer;

public class segment_2243 {
    static long[] tree;
    static long[] arr;
    static int N,tree_size;
    static StringTokenizer st;
    static long ret;
    public static void update(int node, int start, int end, int index, long diff){
        if(!(start <= index &#038;&#038; index <= end)) return;
        tree[node] += diff;
        if(start != end){
            int mid = (start + end ) >> 1;
            update(node * 2, start, mid, index, diff);
            update(node * 2 + 1, mid + 1, end, index, diff);
        }
    }
    public static long query(int node, int start, int end, int k){
        if(start == end){
            System.out.println(start + " ");
            return start;
        }
        if(node *2 <= tree_size &#038;&#038; tree[node * 2] >= k){
            return ret = query(node *2, start, (start + end) / 2, k);
        }
        k -= tree[node * 2];
        if(node * 2 + 1 <= tree_size &#038;&#038; tree[node * 2 + 1] >= k){
            return ret = query(node * 2 + 1, (start + end) / 2 + 1, end, k);
        }
        return 0;
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        int h = (int)Math.ceil(Math.log(1000000) / Math.log(2));
        tree_size = 1 << h + 1;
        tree = new long[tree_size];
        arr = new long[N + 1];
        for (int i = 0; i < N ; i++) {
            int A,B,C;
            st = new StringTokenizer(br.readLine());
            A =  Integer.parseInt(st.nextToken());
            if(A == 1){
                B = Integer.parseInt(st.nextToken());
                int getIndex = (int) query(1, 0,  1000000, B);
                update(1, 0, 1000000, getIndex, -1);
            }
            else if(A == 2){
                B = Integer.parseInt(st.nextToken());
                C = Integer.parseInt(st.nextToken());
                update(1, 0, 1000000, B, C);
            }
        }
    }
}
</code></pre>
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2020/12/22/mst_example_1/">[문제풀이] 군사도로망</a></li><li><a href="https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/">[Algorithms] 투 포인터 알고리즘</a></li><li><a href="https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/">[Algorithms] 위상 정렬 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/">[Algorithms] BFS, DFS 알고리즘</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2021/01/11/acmicpc-2243/">[문제풀이] 사탕 상자</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2021/01/11/acmicpc-2243/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1630</post-id>	</item>
		<item>
		<title>[Algorithms] BFS, DFS 알고리즘</title>
		<link>https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/</link>
					<comments>https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 28 Dec 2020 01:02:47 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1643</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 기본 알고리즘중 하나인 BFS, DFS 알고리즘에 대해서 정리를 해보도록 하겠습니다. 그래프의 모든 노드를 방문하는 알고리즘으로, 면접시에도 많이 나오는 내용이라 필히 알아둬야 할 내용입니다 . 1. DFS 알고리즘 Depth First Search의 의미로, 스택을 기반으로 계속해서 깊게 다음노드로 들어가서 검색을 하는 알고리즘입니다. depth아래로 더이상 내려갈 공간이 없으면, 상위의 스택에서 다음 노드가 있는지&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/">[Algorithms] BFS, DFS 알고리즘</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 기본 알고리즘중 하나인 BFS, DFS 알고리즘에 대해서 정리를 해보도록 하겠습니다. 그래프의 모든 노드를 방문하는 알고리즘으로, 면접시에도 많이 나오는 내용이라 필히 알아둬야 할 내용입니다 .

<h2>1. DFS 알고리즘</h2>

Depth First Search의 의미로, 스택을 기반으로 계속해서 깊게 다음노드로 들어가서 검색을 하는 알고리즘입니다. depth아래로 더이상 내려갈 공간이 없으면, 상위의 스택에서 다음 노드가 있는지 검색을 수행하게 됩니다. 이런식으로 수행하는 방식이 바로 DFS 알고리즘입니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/DFS_1.png?w=1200&#038;ssl=1" alt="DFS_1" />

DFS알고리즘을 구현하기 위해서는 2개의 variable이 필요합니다.

<ul>
<li>map : 2차원 배열로 인접 행렬 방식으로 두 노드간의 연결 정보를 나타냅니다.</li>
<li>visit : 1차원 배열로 노드의 방문을 표기하게 됩니다.</li>
</ul>

<pre><code class="language-java line-numbers">for (int i = 0; i < E; i++) {
    st = new StringTokenizer(br.readLine());
    from = Integer.parseInt(st.nextToken());
    to = Integer.parseInt(st.nextToken());
    map[from][to] = 1;
    map[to][from] = 1;
}
</code></pre>

input정보는 위와 같이 받게 됩니다. 양방향 행렬로 from, to 를 받습니다.

<pre><code class="language-java line-numbers"> public static void dfs(int src) {
        visit[src] = 1;
        System.out.printf(src + " ");
        for (int i = 1; i <= V; i++) {
            if (visit[i] == 0 &#038;&#038; map[src][i] == 1) {
                dfs(i);
            }
        }
    }
</code></pre>

실질적으로 위와 같이 dfs 함수를 작성합니다. dfs의 동작 방식은, 조건에 맞는 노드가 있으면 해당 노드로 계속해서 스택을 쌓으면서 움직이는 것입니다.

가령 1번 노드에서 시작을 하게 되면, 1번 노드와 연결되어있는 다음 노드를 map 인접 행렬에서 찾습니다. 찾고 난다음에는 해당 노드로 다시 dfs함수를 스택으로 쌓으면서 이동하게 됩니다.

<h2>2. BFS 알고리즘</h2>

Breadth-First Search로 알려진 너비 우선 탐색에 대한 알고리즘입니다. 루트노드로부터 시작해서 다음 으로 연결된 모든 노드를 순차적으로 방문을 하는 방식입니다. 그래서 depth별로 각층에 해당 하는 노드를 모두 탐색한 뒤, 더 깊은 depth로 들어가는 방식입니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/DFS_1.png?w=1200&#038;ssl=1" alt="BFS_1" />

BFS는 위에 보시는 것처럼 루트노드를 시작으로 다음 Depth로 이동하면서 각 층에 모든 노드에 대해서 방문을 수행합니다.

BFS 알고리즘을 구현하기 위해서는 역시 2개의 variable이 필요합니다.

<ul>
<li>map : 2차원 배열로 인접 행렬 방식으로 두 노드간의 연결 정보를 나타냅니다.</li>
<li>visit : 1차원 배열로 노드의 방문을 표기하게 됩니다.</li>
</ul>

DFS와 동일하게 input정보는 받게 됩니다.

<pre><code class="language-java line-numbers">public static void bfs(int src) {
        q.offer(src);
        visit[src] = 1;
        while (!q.isEmpty()) {
            int x = (int) q.poll();
            visit[x] = 1;
            System.out.printf(x + " ");
            for (int i = 1; i <= V; i++) {
                if (visit[i] == 0 &#038;&#038; map[x][i] == 1) {
                    q.offer(i);
                    visit[i] = 1;
                }
            }
        }
    }
</code></pre>

BFS 알고리즘은 위와 같이 queue를 이용하게 됩니다. queue에서 뽑아서, 인접 행렬에 연결된 방문하지 않은 노드를 탐색하게 됩니다. dfs와 다른것은 방문을 하고 바로 이동하는 것이 아니라, 해당 depth에서 방문하지 않은 모든 노드를 탐색하게 됩니다. 그리고나서 while문을 통해서 바로 다음 depth로 이동하게 됩니다.

<h2>3. DFS 와 BFS 차이점</h2>

우선 DFS/BFS 같은 경우 다음과 같은 시간 복잡도를 갖고 있습니다 .

<ul>
<li>인접 리스트로 표현된 그래프 : O(V+E)</p></li>
<li>인접 행렬로 표현된 그래프 : O(V^2)</p></li>
</ul>

DFS의 장점으로는 BFS보다 찾고자 하는 정점이 depth가 깊게 있는데서 유리합니다. 
BFS의 장점으로는 최단경로에서 이용할 수 있는 알고리즘입니다.

<img decoding="async" src="https://t1.daumcdn.net/cfile/tistory/997C3C3E5BD01AF41D" alt="BFS_DFS_DIFF" />

<h2>4. 관련 알고리즘 문제</h2>

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/1260" target="_blank" rel="noopener">DFS와 BFS</a>

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/2606" target="_blank" rel="noopener">바이러스</a>

<h2>5. 마치며...</h2>

<h2>6. 출처</h2>

<a class="wp-editor-md-post-content-link" href="https://covenant.tistory.com/132" target="_blank" rel="noopener">DFS BFS란? 백준 문제추천</a>

<a class="wp-editor-md-post-content-link" href="https://yunyoung1819.tistory.com/86" target="_blank" rel="noopener">깊이 우선 탐색 과 너비 우선 탐색</a>

<a class="wp-editor-md-post-content-link" href="https://velog.io/@kjh107704/%EA%B7%B8%EB%9E%98%ED%94%84-BFS%EC%99%80-DFS" target="_blank" rel="noopener">BFS와 DFS</a>
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/">[Algorithms] 투 포인터 알고리즘</a></li><li><a href="https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/">[Algorithms] 위상 정렬 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/14/algorithms-lca/">[Algorithms] LCA 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/03/bellman-ford/">[Algorithms] 벨만-포드 알고리즘</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/">[Algorithms] BFS, DFS 알고리즘</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1643</post-id>	</item>
		<item>
		<title>[문제풀이] 군사도로망</title>
		<link>https://blog.wonizz.com/2020/12/22/mst_example_1/</link>
					<comments>https://blog.wonizz.com/2020/12/22/mst_example_1/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Tue, 22 Dec 2020 02:40:04 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1581</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>1. 설명 군사도로망 문제 어떤 나라는 NN개의 도시로 구성되어 있다. 도시들을 연결하는 도로들이 있는데, 도로라는 것은 서로 다른 두 도시를 연결하는 기능을 하며, 양방향 통행이 가능하고 하나의 도시 쌍에 대해서는 최대 하나의 도로만이 존재 가능한 것으로 가정한다. 이 나라는 몇 년간 전쟁을 치르고 있어서 많은 도로가 파괴된 상태이다. 이제 도로들을 정비하여 모든 쌍의 도시가 단&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/12/22/mst_example_1/">[문제풀이] 군사도로망</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<h2>1. 설명</h2>

<a class="wp-editor-md-post-content-link" href="http://koitp.org/problem/MILITARY_ROAD_NETWORK/read/" target="_blank" rel="noopener">군사도로망</a>

<h3>문제</h3>

<hr />

어떤 나라는 NN개의 도시로 구성되어 있다. 도시들을 연결하는 도로들이 있는데, 도로라는 것은 서로 다른 두 도시를 연결하는 기능을 하며, 양방향 통행이 가능하고 하나의 도시 쌍에 대해서는 최대 하나의 도로만이 존재 가능한 것으로 가정한다. 이 나라는 몇 년간 전쟁을 치르고 있어서 많은 도로가 파괴된 상태이다. 이제 도로들을 정비하여 모든 쌍의 도시가 단 하나의 길(길은 이어서 갈수 있는 도로들을 말함)로 연결되도록 하고 싶다. 군사적인 이유로, 두 도시를 연결하는 길이 두 가지 이상 존재하는 것을 원하지 않기 때문이다. 모든 쌍의 도시 사이에 도로를 만들 수 있는 것은 아니라서, 한 쌍의 도시가 있는 경우 이들 사이에는 이미 도로가 존재, 도로를 만드는 것이 가능, 도로를 만드는 것이 불가능한 세가지 경우가 존재할 수 있다. 도로 정비 과정에서 존재하는 도로를 제거해야 하는 경우도 있음에 주의하라. 각 도로는 만들거나 제거할 때는 비용이 발생하며 비용은 도로마다 다를 수 있다. (이 나라는 가상의 세계에 존재하는 것이므로 서로 다른 두 도로가 교차하는 문제는 전혀 고려할 필요가 없다.)

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/MST_1_1.png?w=1200&#038;ssl=1" alt="MST_1_1" />

위의 그림에 하나의 예가 제시되어 있다. 왼쪽이 초기 상태인데, 이 나라는 55개의 도시로 구성되어 있으며, 33개의 실선으로 표시된 도로는 기존에 존재하는 것이며, 33개의 점선으로 표시된 도로는 건설이 가능한 것이다. 문제의 조건을 만족하면서 최소의 비용을 지불하는 방법은 도시 11과 22 사이의 도로를 제거하고 (비용 11) 도시 33과 55 사이와 도시 44와 55 사이의 도로를 건설하여 (비용 66), 오른쪽 그림과 같은 상태를 만드는 것이다. 총 비용은 77이 된다. 이 예에서 모든 경우들을 따져 보면 정답은 유일함을 알 수 있다.

도시의 수, 지금 존재하는 MM개의 도로들과 각 도로를 제거하는 비용, 도로를 건설하는 것이 가능한 KK개의 도시의 쌍과 각 도로의 건설 비용을 받아서 위의 목적을 달성하는 비용의 최소값과 그 최소값을 달성하는 방법이 유일한 지를 확인하는 프로그램을 작성하라.

<h3>입력</h3>

<hr />

첫 줄에 자연수 세 개가 주어지는데, 첫 수는 N(1≤N≤100,000)N(1≤N≤100,000), 둘째 수는 M(0≤M≤300,000)M(0≤M≤300,000), 셋째 수는 K(0≤K≤300,000)K(0≤K≤300,000)이다. MM이나 KK가 00일 수도 있음에 주의하라. 하지만, 둘 다 00인 경우는 없다. 도시들은 11 부터 NN까지 번호가 붙은 것이다.

이후 MM개의 줄에 기존에 존재하는 각 도로에 대해서 양쪽 끝 도시의 번호와 도로를 제거하는 비용이 33개의 자연수로 주어진다.

이후 KK개의 줄에 건설이 가능한 도로들에 대해서 양쪽 끝 도시의 번호와 건설하는 비용이 주어진다.모든 비용 값은 109109 보다 크지 않은 자연수이며, 항상 목적을 달성할 수 있도록 입력이 주어진다.

<h3>출력</h3>

<hr />

첫 줄에 최소 비용의 값을 자연수로 출력한다. 다시 한 칸을 떼고 최소비용을 만든 방법이 유일한 경우 &#8220;unique&#8221;, 그렇지 않은 경우 &#8220;not unique&#8221;를 따옴표 제외하고 출력한다.

<h3>입력예제</h3>

<pre><code class="line-numbers">1
5 3 3
1 2 1
1 3 4
2 3 2
3 5 2
3 4 7
4 5 4
</code></pre>

<h3>출력예제</h3>

<pre><code class="line-numbers">7
</code></pre>

<h2>2. 문제풀이</h2>

처음에 문제를 봤을때, MST라는 것을 미리 생각하는것이 중요합니다. MST문제의 대부분은 연결을 하되, 싸이클이 생기지 않으면서 동시에 간선의 합이 최소로 가는것입니다.

그런데 이문제를 보면, 연결을 하기만 하는것이 아니고, 연결이 되어있는 것을 없애는 것도 있다.

즉, 연결을 없애는 것 + 연결을 하는것 = 정답 으로 기록하면 됩니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/MST_1_2.png?w=1200&#038;ssl=1" alt="MST_1_2" />

좌측으로는 연결되어있는 3개의 노드가 들어와 있고, 오른쪽에는 연결이 가능한 노드들이 있습니다.

크루스칼을 사용할때, 좌측에서는 기존 크루스칼 학습의 반대(간선을 내림차순으로 정렬하고 하나씩 연결하되, 싸이클이 생길떄 마다 간선값 합산)로 계산을 해주고, 오른쪽은 기존방식(간선을 오름차순으로 정렬하고 하나씩 연결하면서 간선값을 합산하고, 싸이클이 생기면 넘어간다)로 정리를 할 수 있습니다.

<h3>풀이</h3>

<hr />

<pre><code class="language-java line-numbers">import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;
import java.util.Vector;

public class MST_군사도로망 {
    static Vector<kruscal> edge1, edge2;
    static int T, n,m,k; // 3, 3
    static long res;     //long 주의
    static boolean chk;
    static int[] parent;

    //크루스칼 객체 (정점에 정보를 저장하는 객체)
    static class kruscal{
        int from, to, val;
        public kruscal(int from, int to, int val) {
            this.from = from;
            this.to = to;
            this.val = val;
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        st = new StringTokenizer(br.readLine());
        T =  Integer.parseInt(st.nextToken());

        //1. 테스트 케이스
        for (int i = 1; i <= T; i++) {
            res = 0;
            st = new StringTokenizer(br.readLine());
            n = Integer.parseInt(st.nextToken()); //정점의 갯수

            m = Integer.parseInt(st.nextToken()); //연결된 갯수
            k = Integer.parseInt(st.nextToken()); //미연결된 갯수

            parent = new int[n+1];
            for (int j = 1; j <= n; j++)
                parent[j] = j;

            //1. 그래프 형성
            edge1 = new Vector<kruscal>();
            for (int q = 0; q < m; q++) {
                st = new StringTokenizer(br.readLine());
                kruscal ks = new kruscal(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
                edge1.add(ks);
            }

            edge2 = new Vector<kruscal>();
            for (int w = 0; w < k; w++) {
                st = new StringTokenizer(br.readLine());
                kruscal ks = new kruscal(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
                edge2.add(ks);
            }
            //2. 정렬
            Collections.sort(edge1, new Comparator<kruscal>() {
                @Override
                public int compare(kruscal o1, kruscal o2) {
                        if(o1.val < o2.val) return 1;
                        else if(o1.val == o2.val) return 0;
                        else return -1;
                    }
            });
            Collections.sort(edge2, new Comparator<kruscal>() {
                @Override
                public int compare(kruscal o1, kruscal o2) {
                    if(o1.val < o2.val) return -1;
                    else if(o1.val == o2.val) return 0;
                    else return 1;
                }
            });

            ///////////////////////////////////////////////////////////////////////

            //3. 실제 작업.
            for (int a = 0; a < m; a++) {
                merge(edge1.get(a).from, edge1.get(a).to);
                if(!chk)
                    res += edge1.get(a).val;
            }

            for (int b = 0; b < k; b++) {
                merge(edge2.get(b).from, edge2.get(b).to);
                if(chk)
                    res += edge2.get(b).val;
            }
            System.out.println("#" + i + " " + res);

        }
    }
    public static int find(int u){
        if(u == parent[u])
            return u;
        return parent[u] = find(parent[u]);
    }
    public static void merge(int u, int v){
        chk = false;
        u = find(u);
        v = find(v);
        if(u==v) return;
        parent[u] = v;
        chk = true;
    }
}
</code></pre>
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2021/01/11/acmicpc-2243/">[문제풀이] 사탕 상자</a></li><li><a href="https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/">[Algorithms] 투 포인터 알고리즘</a></li><li><a href="https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/">[Algorithms] 위상 정렬 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/">[Algorithms] BFS, DFS 알고리즘</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/12/22/mst_example_1/">[문제풀이] 군사도로망</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/12/22/mst_example_1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1581</post-id>	</item>
		<item>
		<title>[Algorithms] LCA 알고리즘</title>
		<link>https://blog.wonizz.com/2020/12/14/algorithms-lca/</link>
					<comments>https://blog.wonizz.com/2020/12/14/algorithms-lca/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 14 Dec 2020 07:59:18 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1633</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 이진트리에서 최저 공통 조상을 찾아나가는 알고리즘인 LCA(Lowest Common Ancestor) 알고리즘에 대해서 정리를 해보도록 하겠습니다. LCA 알고리즘은 최소 공통 조상을 찾는 알고리즘이고, 트리의 두 노드로부터 최적의 공통 노드를 찾아 나가는 알고리즘입니다. 1. LCA 알고리즘 원리 공통 조상을 찾기 위해서는 다음과 같은 트리가 있다고 가정합니다. 1번 노드가 최상위 루트 노드이고, 밑으로 child들이&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/12/14/algorithms-lca/">[Algorithms] LCA 알고리즘</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 이진트리에서 최저 공통 조상을 찾아나가는 알고리즘인 LCA(Lowest Common Ancestor) 알고리즘에 대해서 정리를 해보도록 하겠습니다.

LCA 알고리즘은 최소 공통 조상을 찾는 알고리즘이고, 트리의 두 노드로부터 최적의 공통 노드를 찾아 나가는 알고리즘입니다.

<h2>1. LCA 알고리즘 원리</h2>

공통 조상을 찾기 위해서는 다음과 같은 트리가 있다고 가정합니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/lca_1.png?w=1200&#038;ssl=1" alt="lca_1" />

1번 노드가 최상위 루트 노드이고, 밑으로 child들이 달린 트리로 구성이 되어있습니다.

여기서 LCA(14, 7)을 요청하게 되면, 어떤값이 나올까요? 답은 1입니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/lca_2.png?w=1200&#038;ssl=1" alt="lca_2" />

그렇다면, LCA(9, 10)은 무엇일까요? 답은 2입니다

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/lca_3.png?w=1200&#038;ssl=1" alt="lca_3" />

LCA(12, 6)은  무엇일까요? 답은 12입니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/lca_4.png?w=1200&#038;ssl=1" alt="lca_4" />

이제 공통 조상에 대한 감이 오시나요? 위로 거슬러 올라가면서 만날 수 있는 최단의 노드가 공통조상이 됩니다.

알고리즘을 이해하기 위해서는 DP식을 이해해야합니다. LCA같은 경우는 input이 양방향으로 들어오게 됩니다. 그리고 depth와 parent배열을 이용해서 다음과 같은 모습으로 트리를 구성하게 되빈다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/lca_5.png?w=1200&#038;ssl=1" alt="lca_5" />

이떄 parent배열은 parent[ i ] [ k ]와 같이 채워지게 되는데, i의 2^k번째 노드의 값이 채워지게 됩니다.

LCA는 이러한 2^k번째를 이용해서 훨씬 빠르게 노드를 검색하게 됩니다. 공통 조상을 구해나가는 알고리즘의 흐름은 다음과 같습니다.

<ul>
<li>두 노드간의 depth가 더 깊은 것을 동일 선상으로 맞추는 작업</li>
<li>조상배열을 통해서 공통의 조상 바로 밑까지 올리는 작업</li>
</ul>

예를들어 LCA(5, 6)을 수행한다고 가정합니다. 아래그림처럼 6의 노드가 depth가 더 깊기때문에 5의 depth까지 맞추는 작업을 수행해야합니다. 하지만, parent는 2^k로 위로 거슬러 올라가기때문에 2^2번째가 되게 되면, 5번 노드보다 값이 더 작아지게 됩니다.

그래서 1차로는 2^1번째 노드인 2번 노드까지 올리게됩니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/lca_6.png?w=1200&#038;ssl=1" alt="lca_6" />

그리고 나서 2번 노드에서 다시 parent배열을 통해서 2^0번번째인 depth 2까지 올리게 됩니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/lca_7.png?w=1200&#038;ssl=1" alt="lca_7" />

그리고 나서, 최종적으로 같은 depth로부터 위로 찾아나가면서 공통적인 노드를 반환합니다. 이것이 바로, LCA를 구하는 알고리즘의 동작 방식입니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/lca_8.png?w=1200&#038;ssl=1" alt="lca_8" />

<h2>2. 초기화 과정</h2>

LCA 알고리즘에서 필요한 변수는 크게 다음과 같습니다.

<ul>
<li>parent : 2차원 배열로 선언하여, i의 2^K번째 노드를 찾아나갈 때 사용하는 변수 입니다.</li>
<li>ad : 필자 같은 경우 인접리스트를 ArryList안에 ArrayList로 구현을 했습니다.</li>
<li>depth : 1차원 배열로 현재 노드의 depth를 타나내는 변수입니다.</li>
</ul>

<h3>2-1. BFS를 활용한 초기 parent 구성</h3>

<pre><code class="language-java line-numbers">c[1] = 1;
q.add(1);
    while(!q.isEmpty()){
        int x = q.poll();
        for (int i = 0; i < ad.get(x).size(); i++) {
            int to = ad.get(x).get(i);
            int y = to;
            if(c[y] == 0){
            depth[y] = depth[x] + 1;
            parent[y][0] = x;
            c[y] = 1;
            q.add(y);
        }
    }
}
</code></pre>

<h3>2-2. DP를 활용한 parent 구성</h3>

<pre><code class="language-java line-numbers">for (int k = 1; k < 17; k++)for (int i = 1; i <= n; i++) {
    parent[i][k] = parent[parent[i][k-1]][k-1];
}
</code></pre>

<h2>3. 공통 조상 쿼리 과정</h2>

공통 조상을 쿼리하는 방식은 위에서 설명했다시피, 두개 노드중에서 depth가 더 깊은것을 동일 선상으로 올리는 작업을 1차적으로 수행합니다.

<pre><code class="language-java line-numbers">//depth를 항상 u가 더 깊게 하기 위해서 swap
if(depth[u] < depth[v]){
    int temp;
    temp = u;
    u = v;
    v = temp;
}
int diff = depth[u] - depth[v];

//두 노드간의 depth차이 만큼 u를 맞춰주는 작업을 수행합니다.
for (int k = 0; diff != 0; k++) {
    if((diff &#038; 1 )== 1) u = parent[u][k];
    diff >>= 1;
}

//두개가 동일하다면 u를 반환합니다.
if(u == v) return u;
</code></pre>

2개의 노드가 동일 선상으로 맞춰졌다면, parent 배열로부터 2개의 노드가 달라지는 위치로 계속해서 노드를 업데이트 해줍니다. 그렇게 되면, 17번의 for문이 모두 돌고 나면, 공통조상의 마래 아래 depth의 노드까지 올라온것을 확인 할 수 있습니다.

<pre><code class="language-java line-numbers">for (int k = 17; k >= 0; k--) {
if(parent[u][k]!= parent[v][k]){
        u = parent[u][k];
        v = parent[v][k];
    }
}

return parent[u][0];
</code></pre>

<h2>4. 관련 알고리즘 문제</h2>

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/3176" target="_blank" rel="noopener">도로 네트워크</a>

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/1761" target="_blank" rel="noopener">정점들의 거리</a>

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/11437" target="_blank" rel="noopener">LCA</a>

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/11812" target="_blank" rel="noopener">K진 트리</a>

<h2>5. 마치며...</h2>
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/">[Algorithms] 투 포인터 알고리즘</a></li><li><a href="https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/">[Algorithms] 위상 정렬 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/">[Algorithms] BFS, DFS 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/03/bellman-ford/">[Algorithms] 벨만-포드 알고리즘</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/12/14/algorithms-lca/">[Algorithms] LCA 알고리즘</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/12/14/algorithms-lca/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1633</post-id>	</item>
		<item>
		<title>[Algorithms] 세그먼트 트리</title>
		<link>https://blog.wonizz.com/2020/12/07/segment-tree/</link>
					<comments>https://blog.wonizz.com/2020/12/07/segment-tree/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 07 Dec 2020 01:02:15 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1623</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 알고리즘 자료구조중 가장 많은 활용도를 보이는 세그먼트 트리에 대해서 정리를 해보도록 하겠습니다. 세그먼트 트리는 여러개의 데이터가 연속적으로 존재할 때 특정한 범위의 데이터의 합을 구하는 방법에 관한 것입니다. 예를들어, 배열에 1 2 3 4 5 라는 내용이 들어있다고 가정합니다. 배열의 이름은 arr이고, index의 시작은 1이라고 가정합니다. 2번째 부터 5번째의 구간의 수를&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/12/07/segment-tree/">[Algorithms] 세그먼트 트리</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 알고리즘 자료구조중 가장 많은 활용도를 보이는 <strong>세그먼트 트리</strong>에 대해서 정리를 해보도록 하겠습니다.

세그먼트 트리는 여러개의 데이터가 연속적으로 존재할 때 특정한 범위의 데이터의 합을 구하는 방법에 관한 것입니다. 예를들어, 배열에 1 2 3 4 5 라는 내용이 들어있다고 가정합니다. 배열의 이름은 arr이고, index의 시작은 1이라고 가정합니다.

2번째 부터 5번째의 구간의 수를 더하라고 가정을 하면, 쿼리는 arr[2] + arr[3] + arr[4] + arr[5]가 될 것입니다. 여기서 다시 3번째 수를 6으로 변경하고, 더하는 수를 다시 구하면, 쿼리는 arr[2] + arr[3] + arr[4] + arr[5]가 됩니다. 변경하는 쿼리는 O(1)이지만, 합을 구하는 쿼리는 O(N)만큼이 들게 됩니다. 그리고 M번의 작업을 진행하게 되면 O(NM)만큼의 시간복잡도가 걸리게 됩니다.

<h2>1. 세그먼트 트리란?</h2>

위의 설명에서 시간복잡도 관련해서 기존 방식으로는 수가 커질수록 시간 복잡도가 많이 소모된다는 것을 알 수 있습니다.

세그먼트 트리에서는 다음과 같은 시간 복잡도를 갖습니다.

<ul>
<li>수를 바꾸는 과정 (O(logN))</li>
<li>수를 더하는 과정(O(logN))</li>
<li>M번 수행한다고 가정하면, O(MlogN + MlogN) -> O(MlogN)이 걸리게 됩니다.</li>
</ul>

세그먼트 트리를 구성하기 위해서는 2개의 배열을 구성합니다. 실제 트리를 구성해주는 tree배열과, 인풋 정보에 대한 배열인 arr 배열을 설명합니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%84%B8%EA%B7%B8%EB%A8%BC%ED%8A%B8%ED%8A%B8%EB%A6%AC_1.png?w=1200&#038;ssl=1" alt="세그먼트트리_1" />

<h2>2. 초기화 과정(Init)</h2>

초기화라는 의미는 트리에 대한 정보를 초기 셋팅해주는 상태를 말합니다. 구간에 대한 합정보를 상위 노드가 담고 있습니다. 아래의 그림과 같은 구성이 되어집니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%84%B8%EA%B7%B8%EB%A8%BC%ED%8A%B8%ED%8A%B8%EB%A6%AC_2.png?w=1200&#038;ssl=1" alt="세그먼트트리_2" />

arr의 배열은 다음과 같이 구성되어있습니다.

arr = {3, 5, 6, 7, 2, 9, 4, 5, 2, 8, 1, 5}

<pre><code class="language-java line-numbers"> public static long init(int node, int start, int end){
        if(start == end) return tree[node] = arr[start];
        int mid = (start + end) >> 1;
        return tree[node] = init(node * 2, start, mid) + init(node * 2 + 1, mid + 1, end);
    }
</code></pre>

시작되는 node에 대한 정보, 그리고 start, end지점에 대해서 초기화를 거칩니다.

위의 그림을 초기화 해보겠습니다.

<pre><code class="language-java line-numbers">init(1, 0, 12);
1번의 tree Node
0 ~ N(12) 까지의 arr 배열 정보
</code></pre>

<pre><code class="language-java line-numbers">if(start == end) return tree[node] = arr[start];
</code></pre>

init 함수에서 위의 코드를 잘 보아야합니다. start <span class="text-highlighted-inline" style="background-color: #fffd38;"> end 가 같아지는 경우, arr[start]정보를 tree[node]지점에 넣어주게 됩니다. </span>

트리구조는 완벽한 2진트리로 구성이 되어지고, 계속해서 child를 좌/우측 노드로 갖게 됩니다. 그래서 초기에 들어온 정보에 대해서 좌/우로 나눠져 내려가다가 말단 노드(Leaf)가 되어지면, 해당 정보를 업데이트 하게 됩니다.

재귀형식으로 구현되어있는 함수이므로, 스택이 계속해서 쌓여나가고 말단 노드부터 차곡차곡 위로 올라가면서 값을 합산하게 됩니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%84%B8%EA%B7%B8%EB%A8%BC%ED%8A%B8%ED%8A%B8%EB%A6%AC_3.png?w=1200&#038;ssl=1" alt="Algorithms 세그먼트 트리 설명 이미지 1" />

위의 그림에서 보시면, 제일 마지막 노드로 내려가서 Init(21, 4, 4)를 나타내고, start <span class="text-highlighted-inline" style="background-color: #fffd38;"> end이기 떄문에 tree[21] = arr[4]를 업데이트 하게 됩니다. 이런식으로 재귀적으로 호출을 하게되면, 위의 그림과 같이 tree의 초기값이 입력이 됩니다. </span>

<h2>3. 갱신 과정(Update)</h2>

갱신 과정은 특정 말단 노드의 값을 A->B로 변경하는 방법에 대한 내용입니다. 아래의 그림처럼, 특정 값을 업데이트를 하게 되면, 그 상위의 관연관되어있는 부모 노드에 대해서도 값을 업데이트를 해주어야 합니다 .

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%84%B8%EA%B7%B8%EB%A8%BC%ED%8A%B8%ED%8A%B8%EB%A6%AC_4.png?w=1200&#038;ssl=1" alt="세그먼트트리_4" />

위의 그림에서 보면, arr[4] = 2였던 값을, 10으로 변경하고자 합니다. 그렇게 되면, 상위의 모든 부모 노드들에 대해서도 diff(업데이트하는 value의 차이)만큼 업데이트를 해주어야 합니다.

<pre><code class="language-java line-numbers">public static void update(int node, int start, int end, int index, long diff){
        if(!(start <= index &#038;&#038; index <= end)) return;
        tree[node] += diff;
        if(start != end){
            int mid = (start + end) >> 1;
            update(node * 2, start, mid, index, diff);
            update(node * 2 + 1, mid + 1, end, index, diff);
        }
    }
</code></pre>

위의 코드가 실제로 업데이트를 하는, 내용입니다.

update(1, 0, 11, 4, 8)의 의미는, tree의 1번 노드에서, 말단 노드의 0~11번 노드까지 훑으면서 4번째의 값을 8만큼의 차리로 업데이트를 해준다는 내용입니다.

역시 재귀적으로 짜여져있습니다.

<pre><code class="language-java line-numbers">if(!(start <= index &#038;&#038; index <= end)) return;
</code></pre>

실제 업데이트하는 index가 말단 노드사이에 없으면, return을 합니다.

<pre><code class="language-java line-numbers">tree[node] += diff;
if(start != end){
    int mid = (start + end) >> 1;
    update(node * 2, start, mid, index, diff);
    update(node * 2 + 1, mid + 1, end, index, diff);
}
</code></pre>

그다음의 코드는, 실제 tree의 값을 업데이트하고, 자식으로 업데이트 정보를 넘기는 내용입니다. 이런식으로 계속해서 내려가면서 정보를 업데이트를 해주게 됩니다.

<h2>4. 구간합 과정(sum)</h2>

구간합을 구하는 과정은, 크게 4가지로 생각해 볼 수 있습니다.

<ol>
<li>left, right와 start, end가 겹치지 않는 경우</li>
<li>left, right가 start, end를 완전히 포함하는 경우</li>
<li>start, end가 left, right를 완전히 포함하는 경우</li>
<li>left, right와 start, end가 겹치는 경우</li>
</ol>

3,4 같은 경우는 범위를 계속해서 좁히기 위해서 재탐색을 수행합니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/12/%EC%84%B8%EA%B7%B8%EB%A8%BC%ED%8A%B8%ED%8A%B8%EB%A6%AC_5.png?w=1200&#038;ssl=1" alt="세그먼트트리_5" />

위의 그림에서 보면, 8 - 11까지의 숫자에 대한 구간합을 구하는 내용입니다.

update(1, 0, 11, 8, 11) 이고 시작하는 tree의 노드정보에 이어서, 말단 노드의 시작과 끝정보(0 ~ 11), 그리고 구간을 구하고자 하는 left와 right의 내용( 8 ~ 11 )이 파라미터로 들어가게 됩니다.

<pre><code class="language-java line-numbers">public static long sum(int node, int start, int end, int left, int right){
        if(left > end || right < start) return 0; // 범위에 속하지 않으면, return 
        if(left <= start &#038;&#038; end <= right) return tree[node]; // left,right가 완전히 포함하면, tree정보 리턴
        //그외의 경우는 범위를 쪼갠다.
        int mid = (start + end) >> 1;
        return sum(node * 2, start, mid, left, right) + sum(node * 2 + 1, mid +1 , end, left, right);
    }
</code></pre>

<h2>5. 관련 알고리즘 문제</h2>

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/2243" target="_blank" rel="noopener">사탕 상자</a>

<h2>6. 마치며...</h2>

이번시간에는 구간합 및 특정 구간에서의 최대/최소를 구하는데에 대한 최적화 알고리즘인 인덱스트리(세그먼트트리)에 대해서 정리를 해보았습니다. 알고리즘을 공부하면 할 수록 이러한 자료구조에 대한 기본지식이 탄탄해야 된다는 것을 다시한번 느끼게 되었습니다. 
세그먼트 트리를 활용해서 구할 수 있는 문제들에 대해서 좀 더 정리가 필요해보입니다. 관련 알고리즘 문제는 반드시 이해하고 풀이를 다시한번 해야된다는 것을 느끼게 되는 포스팅이였습니다.

다음시간에는 LCA에 대해서 정리를 해보도록 하겠습니다.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2020/11/16/minimum-spanning-tree/">[Algorithms] 최소 스패닝 트리(Minimum Spanning Tree)</a></li><li><a href="https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/">[Algorithms] 투 포인터 알고리즘</a></li><li><a href="https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/">[Algorithms] 위상 정렬 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/">[Algorithms] BFS, DFS 알고리즘</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/12/07/segment-tree/">[Algorithms] 세그먼트 트리</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/12/07/segment-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1623</post-id>	</item>
		<item>
		<title>[Algorithms] 벨만-포드 알고리즘</title>
		<link>https://blog.wonizz.com/2020/12/03/bellman-ford/</link>
					<comments>https://blog.wonizz.com/2020/12/03/bellman-ford/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Thu, 03 Dec 2020 04:22:08 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1614</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 최단거리 알고리즘중 음의 가중치도 계산이 가능한 벨만-포드 알고리즘에 대해서 정리를 해보도록 하겠습니다. 다익스트라보다 시간 복잡도가 높기에 어떤 상황에서 이용해야 할지 잘 생각하여 사용해야합니다. 1. 벨만포드 기본 개념 최단 경로를 구하기 위해서는 다음과 같이 분해를 할 수 있습니다. D(s, v) = D(s, u) + w(u, v) 즉, s->v로 가는 최단 거리는&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/12/03/bellman-ford/">[Algorithms] 벨만-포드 알고리즘</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 최단거리 알고리즘중 음의 가중치도 계산이 가능한 벨만-포드 알고리즘에 대해서 정리를 해보도록 하겠습니다. 다익스트라보다 시간 복잡도가 높기에 어떤 상황에서 이용해야 할지 잘 생각하여 사용해야합니다.

<h2>1. 벨만포드 기본 개념</h2>

최단 경로를 구하기 위해서는 다음과 같이 분해를 할 수 있습니다.

<pre><code class="language-java line-numbers">D(s, v) = D(s, u) + w(u, v)
</code></pre>

즉, s->v로 가는 최단 거리는 s에서 u를 거치는 최단거리에서, u->v로 가는 간선의 정보를 합산한 거리가 최단거리가 된다는 이론입니다. s->u까지의 최단 경로를 구하기 위해서는 그래프내에 모든 노드들에 대해서 거리를 계산해야합니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/%EB%B2%A8%EB%A7%8C%ED%8F%AC%EB%93%9C_1.png?w=1200&#038;ssl=1" alt="벨만포트_1" />

위의 그림에서 보면, 1에서 3으로 가는 최단거리를 구하는것을 생각해 봅시다. 1->3으로 가는것을 다익스트라로 구하게 되면, dist[3] = 6을 입력하고 종료하게 됩니다. 이유는 우선순위 큐에 간선정보가 들어가게 되면, 최단 거리인 6이 입력되고, 해당 값을 사용하면서 종료하게 됩니다. 모든값들이 양수라고 생각하고 설계된 알고리즘입니다. 즉, 12, 6중에서 6을 택한것이 다른 어떠한 값보다 더 최단이 된다고 생각하는 알고리즘입니다.

이전 포스팅에서 기록했지만, 음수에 대한 설계가 되어있지 않습니다. 벨만포드 알고리즘은 1->3으로 가는 모든 사이의 정점에 대해서 조사를 해보자라는 내용입니다. 즉, 최대 갖을 수 있는 숫자인 정점 빼기 1한 만큼의 iteration을 수행하면서 edge relaxation 을 수행하는 알고리즘입니다.

위에서 보면, 2번의 작업을 수행하게 됩니다. 먼저 정점 1번에서 출발하게 되면, dist[2] = 12, dist[3] = 6으로 업데이트를 수행합니다. 그 이후에, 2번 정점에서 출발하게 되고, dist[2] + (-9)를 하게 되면서, dist[3] = 3으로 업데이트를 수행하게 됩니다. 이것이 첫번쨰 iteration 의 종료입니다.
이런식으로 V-1번큼의 iteration을 돌면서 정점에 대해서 체크를 수행합니다.

<h2>2. 벨만-포드 예외사항</h2>

벨만포드 알고리즘은 위에서 보신바와 같이, 음수인 경우에도 적용 가능합니다. 그러나 다음과 같이 음수 가중치가 사이클(cycle)을 이루고 있는 경우에는 동작하지 않습니다. 아래의 그림에서 보면, c,d그리고 e,f가 사이클을 이루고 있는 것을 확인 할 수 있습니다. c,d의 경우에는 사이클을 돌아도 거리가 계속해서 커지지만, e,f같은 경우 사이클을 계속해서 돌게 되면, 음수 무한대로 커지게 됩니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/%EB%B2%A8%EB%A7%8C%ED%8F%AC%EB%93%9C_2.png?w=1200&#038;ssl=1" alt="벨만포드_2" />

<h2>3. 벨만-포드 코드</h2>

우선순위큐 알고리즘과 다른 부분은 1개의 객체에 here, there, cost정보를 담고 있습니다.

<pre><code class="language-java line-numbers">static class Point{
    // 시작점, 도착점, 걸리는 시간
    int here, there, dist;
    public Point(int here, int there, int dist){
        this.here = here;
        this.there = there;
        this.dist = dist;
    }
}
</code></pre>

입력정보는 다음과 같이 받습니다. ArrayList를 따로 사용하지 않고, Point객체를 배열로 선언하여 담습니다.

<pre><code class="language-java line-numbers">// 2. 입력값 초기화
for(int i = 0; i < m; i++){
    st = new StringTokenizer(br.readLine());
    int here = Integer.parseInt(st.nextToken());
    int there = Integer.parseInt(st.nextToken());
    int dist = Integer.parseInt(st.nextToken());
    point[i] = new Point(here, there, dist);
}
</code></pre>

실제 최단 거리를 구하는 수행은 아래의 벨만포드 함수로 작성했습니다. V-1 만큼의 최대간선수의 for문을 수행하고 아래의 내용은 각 정점으로부터 edge relaxation을 수행합니다.

<pre><code class="language-java line-numbers">private static boolean bellmanFord() {
    dist[1] = 0;
    // v - 1번 수행
    for(int i = 1; i < n; i++){
        // edge relaxtaion
        for(int j = 0; j < m; j++){
            Point p = point[j];
            // dist[there] > 현재 정점 + 거리 이면, 최단으로 업데이트 수행
            if(dist[p.here] != INF && dist[p.there] > dist[p.here] + p.dist){
                dist[p.there] = dist[p.here] + p.dist;
            }
        }
    }
}
</code></pre>

위에서 보시는것이 벨만포드의 핵심 알고리즘 입니다. V-1 번만큼의 iteration을 돌면서 1회당 전체 edge에 대해서 relaxation을 수행합니다. 현재의 dist배열에 있는 값이 가려는 정점의 현재 dist배열의 값에 간선정보를 합산한것이 더 작으면 계속해서 dist배열을 업데이트 해줍니다. 이렇게 V-1번의 iteration만큼 진행하면, src정점으로부터 N번째 노드까지의 최단거리를 구하게 됩니다.

dist 배열의 가고자 하는 값이 dist배열의 현재 정점 + 거리를 합한 값보다 크다면 업데이트를 수행합니다.

<h2>4. 관련 알고리즘 문제</h2>

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/11657" target="_blank" rel="noopener">타임머신</a>

<h2>5. 마치며..</h2>

이번시간에는 음수의 간선에 대해서도 최단 거리를 계산이 가능한 벨만포드 알고리즘에 대해서 정리를 해보았습니다. 최단거리하면 다익스트라 알고리즘만 알고 있었는데, 벨만포드 알고리즘을 통해서도 src 정저으로부터 다른 정점에 대한 거리를 구하는 것이 가능합니다. 비록 다익스트라 알고리즘보다는 정점 * 간선의 갯수만큼 시간 복잡도가 나오므로, 좀더 시간이 걸린다는 단점이 있습니다. 하지만, 알고리즘 문제에서 음수의 간선이 나오면 고려를 해볼 수 있는 알고리즘 이라는 것을 알게 되었습니다.

다음시간에는 N개의 정점에서 다른 모든 정점으로의 거리를 구할 수 있는 플로이드-워셜 알고리즘에 대해서 정리를 해보도록 하겠습니다.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/">[Algorithms] 투 포인터 알고리즘</a></li><li><a href="https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/">[Algorithms] 위상 정렬 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/">[Algorithms] BFS, DFS 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/14/algorithms-lca/">[Algorithms] LCA 알고리즘</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/12/03/bellman-ford/">[Algorithms] 벨만-포드 알고리즘</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/12/03/bellman-ford/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1614</post-id>	</item>
		<item>
		<title>[Algorithms] 우선순위 큐 다익스트라</title>
		<link>https://blog.wonizz.com/2020/11/30/dijkstra/</link>
					<comments>https://blog.wonizz.com/2020/11/30/dijkstra/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 30 Nov 2020 05:49:47 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1602</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 최단거리 알고리즘인 다익스트라에 대해서 정리를 해보려고 합니다. 1. 다익스트라 기본 개념 다익스트라 알고리즘은 너비우선탐색(BFS)를 기본으로 합니다. 모든 정점의 거리를 초기에는 무한대로 세팅을 해줍니다. 위의 그림에서 (b)를 보게 되면, 최초 시작 정점인 s로부터 BFS의 알고리즘을 적용하여 2개의 각정점으로 거리를 확인하고 있습니다. s->t로 가는 것은 10으로, s->y로 가는것은 5로 업데이트를 수행합니다. 초기값이&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/11/30/dijkstra/">[Algorithms] 우선순위 큐 다익스트라</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 최단거리 알고리즘인 다익스트라에 대해서 정리를 해보려고 합니다.

<h2>1. 다익스트라 기본 개념</h2>

다익스트라 알고리즘은 너비우선탐색(BFS)를 기본으로 합니다. 모든 정점의 거리를 초기에는 무한대로 세팅을 해줍니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/%EB%8B%A4%EC%9D%B5%EC%8A%A4%ED%8A%B8%EB%9D%BC_1.png?w=1200&#038;ssl=1" alt="다익스트라_1" />

위의 그림에서 (b)를 보게 되면, 최초 시작 정점인 s로부터 BFS의 알고리즘을 적용하여 2개의 각정점으로 거리를 확인하고 있습니다. s->t로 가는 것은 10으로, s->y로 가는것은 5로 업데이트를 수행합니다. 초기값이 무한대로 세팅이 되어있으므로, 무한대보다 모든값들은 작기 때문에, 초기에 BFS를 수행하게 되면 해당 간선 정보로 업데이트를 하게 됩니다.

(c)를 보게되면, 다음 너비우선탐색에서 정점을 호출하게 되고 다음 깊이인 y에서 연결된 간선정보로 확인을 수행하게 됩니다. y->t로 가는 값은 +3이 더해져서 8이 되었습니다. 기존에 s->t로 가는 간선정보인 10보다 8이 더 최단이기 때문에 업데이트를 수행하게 됩니다. 같은 방식으로 y->x, y->z도 모두 확인을 하고 업데이트를 해줍니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/%EB%8B%A4%EC%9D%B5%EC%8A%A4%ED%8A%B8%EB%9D%BC_2.png?w=1200&#038;ssl=1" alt="다익스트라_2" />

(e)를 보게 되면, 정점 t에서 x를 9로 업데이트를 수행하게 됩니다. 그리고 (d)를 보게 되면, 정점 z에서 x로 가는 간선정보인 +6을 더해주게 되어, 13이 되는데 이는 s->y->t->x로 이어지는 9값보다 크게 되어 업데이트를 하지 않습니다. 끝으로 x의 정점을 확인하게 되고 연결되어있는 간선이 없기 때문에 알고리즘을 종료하게 됩니다.

<h2>2. 다익스트라의 단점</h2>

다익스트라 알고리즘의 최대 단점은 가중치가 음수인 경우 작동하지 않는다는 점입니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/%EB%8B%A4%EC%9D%B5%EC%8A%A4%ED%8A%B8%EB%9D%BC_3.png?w=1200&#038;ssl=1" alt="다익스트라_3" />

위의 그림에서 보면, A노드에서 시작합니다. A->C가 간선의 최소이기 때문에 C를 선택하게 됩니다. 그리고 C노드에서 갈수 있는 간선의 방향을 봤더니, C->E가 최소가 되고, 1을 찍고 종료하게 됩니다. 실제로는 A->C>B>E로 가야만, 최단거리가 되겠지만, A->C>E로 간 후 종료를 합니다. 다익스트라 알고리즘은 그리디 알고리즘에 기초를 두고 있습니다. 최소힙에의해서 cost가 가장 최단거리인것만 더해나가기 때문에 위와 같이 음수인 간선에 대해서 처리를 하지 못합니다.

음수인 간선에 대해서는 벨만-포드 알고리즘에 의해서 해결할 수 있습니다. 이부분은 다음번 포스팅에서 정리하도록 하겠습니다.

<h2>3. 우선순위 큐</h2>

기본적으로 다익스트라를 구현하기 위해서는, 시작점이후의 모든 정점에서 한번씩 거리(간선)을 측정해서 합산하면서 계속해서 업데이트를 해줘야 합니다. 그렇게 되면, E+V^2만큼의 시간 복잡도를 갖고 있습니다. 정점의 갯수가 커지면 커질수록 영향도가 더 커지기 때문에 최종적으로는 V^2의 복잡도를 갖고 있습니다.

이렇게 되면, 알고리즘 문제를 해결할 때, 정점의 갯수에 지대한 영향을 받게 됩니다. 따라서, 이부분에서 최적화를 해야되는데 앞서 정리했던 Priority Queue를 이용하면 복잡도를 줄일 수 있습니다. 바로 MinHeap을 이용하게 되는 것인데, 최단 거리(간선정보)를 갖고 있는 정점을 찾기 위해서 탐색을 수행하는데 여기서 logV만큽의 시간 복잡도를 갖고 있습니다. 그래서 최종적으로는 (E+V) * logV의 시간 복잡도를 갖게 됩니다.

Priority queue를 이용함으로써 시간 복잡도를 현저하게 줄일 수 있습니다. 즉, MinHeap(우선순위 큐)를 이용하여 시간 복잡도를 현저하게 줄 일 수 있게 되었습니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/%EB%8B%A4%EC%9D%B5%EC%8A%A4%ED%8A%B8%EB%9D%BC_5.png?w=1200&#038;ssl=1" alt="다익스트라_5" />

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/%EB%8B%A4%EC%9D%B5%EC%8A%A4%ED%8A%B8%EB%9D%BC_6.png?w=1200&#038;ssl=1" alt="다익스트라_6" />

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/%EB%8B%A4%EC%9D%B5%EC%8A%A4%ED%8A%B8%EB%9D%BC_7.png?w=1200&#038;ssl=1" alt="다익스트라_7" />

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/%EB%8B%A4%EC%9D%B5%EC%8A%A4%ED%8A%B8%EB%9D%BC_8.png?w=1200&#038;ssl=1" alt="다익스트라_8" />

위의 그림을 소스의 형태로 나타내 보겠습니다 .

<pre><code class="language-java line-numbers">pq = new PriorityQueue<pqPoint>();
ad = new ArrayList<ArrayList<Point>>();
</code></pre>

필자는 2개의 자료구조를 사용했습니다. pqPoint(here와 cost를 변수로 사용)라는 구조체를 만들고, 이부분을 Priority Queue에다가 담습니다. 그렇게 하고 cost에 따라서 최소힙이 구성되도록 하였습니다.

들어오는 정보(노드, 간선)에 대해서는 인접리스트로 구현하였습니다. 리스트 안에 리스트를 담는 형태로 구성했습니다. Point(there, nextDist) 구조체는 다음에 들어갈 노드정보와 거리 정보입니다.

<pre><code class="language-java line-numbers">for (int i = 0; i < E; i++) {
    st = new StringTokenizer(br.readLine().trim());
    int from, to, value;
    from = Integer.parseInt(st.nextToken());
    to = Integer.parseInt(st.nextToken());
    value = Integer.parseInt(st.nextToken());
    ad.get(from).add(new Point(to, value));
}
</code></pre>

위의 코드는 from, to, value형태로 들어오는 정보에 대해서 인접리스트에 담는 코드 입니다. 보시면, from을 기점으로해서 다음 정점의 노드와, 거리 정보를 담습니다.

<pre><code class="language-java line-numbers">public static void dijkstra(int src){
    pq.add(new pqPoint(src, 0));
    dist[src] = 0;
    while(!pq.isEmpty()){
        pqPoint p= pq.poll();
        int cost = p.cost;
        int here = p.here;
        if(dist[here] < cost) continue;
        for (int i = 0; i < ad.get(here).size(); i++) {
            int there = ad.get(here).get(i).there;
            int nextDist = cost + ad.get(here).get(i).nextDist;
            if(dist[there] > nextDist){
                dist[there] = nextDist;
                pq.add(new pqPoint(there, nextDist));
            }
        }
    }
}
</code></pre>

무엇보다 가장 중요한것이, 위의 함수 입니다. 주어진 정보대로 인접리스트에 잘 담았다면, 최단거리를 알아야될 start 노드를 넣고 다익스트라 함수를 수행합니다. 
우선순위 큐에다가 최초 src(위의 예에서 1이라고 가정)와 dist정보를 넣습니다. 최초 시작점은 자기 자신이기 때문에 0이 들어갑니다.

우선순위 큐에서 최소힙에 의해 구성된 제일 처음 노드정보를 빼옵니다. 처음시작은 한개밖에 넣지 않았으므로, 위의 예에서는 1이 나올 것입니다. 
here = 1, cost = 0 가 나오게되고, dist[1] = INF &lt; 0 에 의해서 넘어갑니다.

<pre><code class="language-java line-numbers">for (int i = 0; i < ad.get(here).size(); i++) {
    int there = ad.get(here).get(i).there;
    int nextDist = cost + ad.get(here).get(i).nextDist;
    if(dist[there] > nextDist){
        dist[there] = nextDist;
        pq.add(new pqPoint(there, nextDist));
    }
}
</code></pre>

위의 부분이 바로 인접리스트에서 정보를 빼오고, for문을 수행하면서 체크를 합니다. 1정점을 빼오면 다음과 같은 정보가 있습니다
there = 2, cost= 0, nextDist = 2 + 0 , dist[2] = INF > 2 이므로 거리를 업데이트하고, pq에 넣는다. 
there = 3, cost= 0, nextDist = 3 + 0,  dist[3] = INF > 3 이므로 거리를 업데이트하고, pq에 넣는다.

그럼 다시, while문에 의해서 queue에서 한개를 빼오게 되면, 
here = 2, cost = 2가 나오게 됩니다. dist[2] = 2 &lt; 2 에 의해서 넘어갑니다.

인접리스트에서 정보를 뺴오고, for문을 수행하면서 체크합니다. 
there = 3, cost = 2, nextDist = 2 + 4, dist[3] = 3 > 6에 의해서 넘어갑니다. 
there = 4, cost = 2, nextDist = 2 + 5, dist[4] = INF > 7 이므로 거리를 업데이트하고, pq에 넣는다.

다시, while문에 의해서 queue에서 한개를 빼오게 되면, 
here =3, cost = 3가 나오게 됩니다. dist[3] = 3 &lt; 3 에 의해서 넘어갑니다.

인접리스트에서 정보를 빼오고, for문을 수행하면서 체크합니다. 
there = 4, cost = 3, nextDist = 3 + 6, dist[4] = 7 > 9 이므로 넘어갑니다.

마지막으로, queue에는 4가 담겨져있지만, 간선정보가 없으므로 바로 빠져나옵니다.

<h2>4. 관련 알고리즘 문제</h2>

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/1753" target="_blank" rel="noopener">최단 경로</a>

<h2>5. 마치며...</h2>

이번시간에는 최단 거리 알고리즘인 다익스트라에 대해서 알아보았습니다. 다익스트라는 음의 정보에 대해서는 처리를 못한다는 단점이 있습니다. 이러한 부분에 대해서는 벨만포드 알고리즘으로 해결을 할 수 있습니다. 다음시간에는 벨만포트 알고리즘에 대해서 정리를 해보도록 하겠습니다.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/">[Algorithms] 투 포인터 알고리즘</a></li><li><a href="https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/">[Algorithms] 위상 정렬 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/">[Algorithms] BFS, DFS 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/14/algorithms-lca/">[Algorithms] LCA 알고리즘</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/11/30/dijkstra/">[Algorithms] 우선순위 큐 다익스트라</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/11/30/dijkstra/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1602</post-id>	</item>
		<item>
		<title>[Algorithms] Heap, Priority Queue</title>
		<link>https://blog.wonizz.com/2020/11/24/priority-queue/</link>
					<comments>https://blog.wonizz.com/2020/11/24/priority-queue/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Tue, 24 Nov 2020 03:24:26 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1591</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 우선순위 큐에 대해서 정리하는 시간을 갖어 보겠습니다. 지난 시간에 이어서 자료구조중 하나로 알고리즘에서 많이 활용되는 형태입니다. 지난시간에 정리를 해뒀지만, 일반적인 Queue의 형태는 First-In First-out의 구조를 보였습니다. 하지만, PQ같은 경우 정해진 우선순위에 따라서, 우선순위가 높은 데이터가 먼저 나오는 것을 말합니다. 우선순위 큐는 힙(Heap)이라는 자료구조를 가지고 구현하기 때문에 이둘을 묶어서 설명을 합니다.&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/11/24/priority-queue/">[Algorithms] Heap, Priority Queue</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 <strong>우선순위 큐</strong>에 대해서 정리하는 시간을 갖어 보겠습니다. 지난 시간에 이어서 자료구조중 하나로 알고리즘에서 많이 활용되는 형태입니다.

지난시간에 정리를 해뒀지만, 일반적인 Queue의 형태는 First-In First-out의 구조를 보였습니다. 하지만, PQ같은 경우 정해진 우선순위에 따라서, 우선순위가 높은 데이터가 먼저 나오는 것을 말합니다.

우선순위 큐는 <strong>힙(Heap)</strong>이라는 자료구조를 가지고 구현하기 때문에 이둘을 묶어서 설명을 합니다.

<h2>1. Heap이란?</h2>

<ul>
<li>완전 이진 트리의 일종으로 우선순위 큐를 위하여 만들어진 자료구조 입니다.</li>
<li>여러개의 값들 중에서 최댓값이나 최솟값을 빠르게 찾아내도록 만들어진 자료구조 입니다.</li>
</ul>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/heap_1.png?w=1200&#038;ssl=1" alt="heap_1" />

<h3>1-1. Heap의 구현</h3>

<ul>
<li>힙을 저장하는 표준적인 자료구조는 배열입니다.</li>
<li>구현을 쉽게 하기 위해서는 첫번째 인덱스인 0은 사용하지 않습니다.</li>
<li>힙에서의 부모 노드와 자식 노드와의 관계

<ul>
<li>왼쪽 자식의 인덱스 = (부모의 인덱스) * 2</li>
<li>오른쪽 자식의 인덱스 = (부모의 인덱스) * 2 + 1</li>
<li>부모의 인덱스 = (자식의 인덱스) / 2</li>
</ul></li>
</ul>

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/heap_2.png?w=1200&#038;ssl=1" alt="heap_2" />

<h3>1-2. heap 의 삽입</h3>

heap에 새로운 요소가 들어가면, 일단 말단 노드에 새로운 노드를 삽입합니다. 그리고 삽입된 노드를 상위의 부모노드와 비교를 수행하면서 재정렬을 수행합니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/heap_3.png?w=1200&#038;ssl=1" alt="heap_3" />

<h3>1-3. heap의 삭제</h3>

heap에서 요소가 삭제되면, 일단 말단 노드를 최상단 노드로 옮겨 옵니다. 그리고 자식의 노드와 비교를 수행하면서 재정렬을 수행합니다.

<img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2020/11/heap_4.png?w=1200&#038;ssl=1" alt="heap_4" />

<h2>2. Priority Queue란?</h2>

우선순위 큐를 활용하는 것은 우리 일생생활에 굉장히 많이 있습니다. 예를들어, 응급실에서 환자를 들어오는 순서대로 본다면 어떻게 될까요? 중증, 경증에 따라 우선순위를 둬야 하고 좀더 긴박한사람에 대해서 빠른 응급조치를 해야될 것입니다.

<h3>2-1. Priority Queue의 구현</h3>

<pre><code class="line-numbers"> public class Sample {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(4);
        pq.add(19);
        pq.add(2);
        pq.add(1);
        System.out.println(pq.poll()); // 1이 출력된다.
    }
}
</code></pre>

위의 예제에서 보시는것처럼, PriorityQueue라는 구현체가 있습니다. Interger object타입을 받을수 있게 셋팅을 해두었고, 각각 add라는 함수를 통해서 넣어주고 있습니다.

기존의 queue 자료구조였다면, poll을 수행하게 되면 4가 노출이 되어야 하지만, 1이 출력이 되고 있습니다. 오름차순으로 정렬이 내부적으로 된것입니다.

<pre><code class="line-numbers">public class Sample {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
        pq.add(4);
        pq.add(19);
        pq.add(2);
        pq.add(1);

        System.out.println(pq.poll()); // 19가 출력된다.
    }
}
</code></pre>

Collection의 reserseOrder라는 함수를 수행하게 되면, 내림차순으로 정렬이 됩니다. 그러면 가장큰수인 10이 출력이 됩니다.

<h3>2-2. Custom 객체에 대한 우선순위 큐 적용</h3>

<pre><code class="line-numbers">class Prisoner {
    String name;
    int weight; // 형량

    public Prisoner(String name, int weight) {
        super();
        this.name = name;
        this.weight = weight;
    }
}
</code></pre>

위의 예제와 같이 <strong>죄수</strong>라는 객체를 생성했습니다. value로는 이름과 형량일라는 값이 있습니다. 이제 우선순위큐에 넣고, 형량이 가장 작은 사람이 출력이 되도록 정렬을 수행하겠습니다.

<pre><code class="line-numbers">class Prisoner implements Comparable<Prisoner> {

    String name;
    int weight; // 형량

    public Prisoner(String name, int weight) {
        super();
        this.name = name;
        this.weight = weight;
    }

    @Override
    public int compareTo(Prisoner target) {
        if (this.weight > target.weight) {
            return 1;
        } else if (this.weight < target.weight) {
            return -1;
        }
        return 0;
    }
</code></pre>

일반적으로는 Custom 객체에 위와 같이 compareTo라는 함수를 오버라이드 하여 구현하게 됩니다. 그렇게 되면, 객체를 생성하여 queue에 넣을때마다, compareTo함수가 동작을 하게 되어, 정렬을 수행합니다.

<pre><code class="line-numbers">private static PriorityQueue<Prisoner> getPriorityQueue() {

    Prisoner prisoner1 = new Prisoner("james", 5);
    Prisoner prisoner2 = new Prisoner("schofield", 99);
    Prisoner prisoner3 = new Prisoner("alex", 14);
    Prisoner prisoner4 = new Prisoner("silvia", 10);
    Prisoner prisoner5 = new Prisoner("thomson", 1);

    PriorityQueue<Prisoner> priorityQueue = new PriorityQueue<Prisoner>();

    priorityQueue.offer(prisoner1);
    priorityQueue.offer(prisoner2);
    priorityQueue.offer(prisoner3);
    priorityQueue.offer(prisoner4);
    priorityQueue.offer(prisoner5);

    return priorityQueue;
}
</code></pre>

객체를 생성하여, 위와 같이 pq에 넣는 과정을 거쳤습니다.

<pre><code class="line-numbers">public static void main(String[] args) {

        PriorityQueue<Prisoner> priorityQueue = getPriorityQueue();
        System.out.println("=============== Normal Order");
        while (!priorityQueue.isEmpty()) {
            Prisoner prisoner = priorityQueue.poll();
            System.out.println(prisoner.name);
        }
}
</code></pre>

<pre><code class="line-numbers">=============== Normal Order
thomson
james
silvia
alex
schofield
</code></pre>

<h2>3. 관련 알고리즘 문제</h2>

<ul>
<li>자료구조 기본 문제</li>
</ul>

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/11279" target="_blank" rel="noopener">최대힙</a>

<h2>4. 마치며..</h2>

이번시간에는 자료구조에 대해서 정리를 해보았습니다. 자바에서 제공해주는 자료구조들은 정말 활용도가 높게 설계가 되어 있습니다. 특히 힙의 자료구조 같은 경우, 트리를 활용해서 정렬을 수행하다보니 수행속도 면에서 굉장히 빠르게 설계가 되어있습니다.

이러한 자료구조를 적절하게 활용한다면 프로그래밍에서도 효율적인 코딩이 가능할 것이라고 생각이 들었습니다.

다음시간에는 최단거리 알고리즘인 다익스트라에 대해서 정리를 해보도록 하겠습니다.

<h2>5. 참조</h2>

<a class="wp-editor-md-post-content-link" href="https://gmlwjd9405.github.io/2018/05/10/data-structure-heap.html" target="_blank" rel="noopener">[자료구조] 힙(heap)이란</a>

<a class="wp-editor-md-post-content-link" href="http://asuraiv.blogspot.com/2015/11/java-priorityqueue.html" target="_blank" rel="noopener">[JAVA] 우선순위(PriorityQueue) 큐</a>
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2021/01/29/algorithms-two-pointer/">[Algorithms] 투 포인터 알고리즘</a></li><li><a href="https://blog.wonizz.com/2021/01/20/algorithms-topological-sort/">[Algorithms] 위상 정렬 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/28/algorithms-bfs-dfs/">[Algorithms] BFS, DFS 알고리즘</a></li><li><a href="https://blog.wonizz.com/2020/12/14/algorithms-lca/">[Algorithms] LCA 알고리즘</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/11/24/priority-queue/">[Algorithms] Heap, Priority Queue</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2020/11/24/priority-queue/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1591</post-id>	</item>
	</channel>
</rss>
