<?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>알고리즘 &#8211; WONIZZ.LOG</title>
	<atom:link href="https://blog.wonizz.com/tag/%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.wonizz.com</link>
	<description>DEVELOPMENT &#38; LIFE LOG</description>
	<lastBuildDate>Fri, 21 Aug 2026 15:45:30 +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>알고리즘 &#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] 최소 스패닝 트리(Minimum Spanning Tree)</title>
		<link>https://blog.wonizz.com/2020/11/16/minimum-spanning-tree/</link>
					<comments>https://blog.wonizz.com/2020/11/16/minimum-spanning-tree/#respond</comments>
		
		<dc:creator><![CDATA[워니]]></dc:creator>
		<pubDate>Mon, 16 Nov 2020 06:19:44 +0000</pubDate>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[알고리즘]]></category>
		<guid isPermaLink="false">http://blog.wonizz.tk/?p=1571</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>그래프의 모든 노드를 포함하고, 모든 노드가 서로 연결되어 있으면서 트리(Tree)의 속성을 만족하는 그래프를 가리킵니다. 예를들어 하단 좌측과 같은 원 그래프의 스패닝 트리는 하단 우측과 같이 총 8개의 스패닝 트리들을 가질 수 있습니다.</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2020/11/16/minimum-spanning-tree/">[Algorithms] 최소 스패닝 트리(Minimum Spanning Tree)</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. 최소 스패닝 트리(Minimum Spanning Tree, MST)란?</h2>

그래프의 모든 노드를 포함하고, 모든 노드가 서로 연결되어 있으면서 트리(Tree)의 속성을 만족하는 그래프를 가리킵니다. 예를들어 하단 좌측과 같은 원 그래프의 스패닝 트리는 하단 우측과 같이 총 8개의 스패닝 트리들을 가질 수 있습니다.

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

최소 신장 트리(MST)는 가능한 신장트리 가운데 엣지 가중치의 합이 최소인 신장트리를 말합니다. 예를들어 하단 좌측과 같은 원 그래프의 MST는 하단 우측과 같습니다 .

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

MST는 노드 간 연결성을 보장하면서 노드 사이를 잇는 거리/비용 등을 최소로 하는 그래프를 의미하기 떄문에 응용 범위가 넓습니다.

<h2>2. 크루스칼 알고리즘</h2>

크루스칼 알고리즘은 모든 간선에 대해 가장 가중치가 작은 간선부터 연결해주면서 최소 스패닝 트리를 만들어 나가는 알고리즘을 의미합니다.

이때 가장 작은 간선부터 간선을 연결하되, <strong>연결하는 도중 사이클이 생기게 되면 가중치가 작은 간선이어도 무시</strong>하여야 합니다.

크루스칼 알고리즘은 <strong>Disjoint set</strong>을 기본 자료구조로 활용합니다.

예를들어, 하단의 (a)를 보겠습니다. 그래프 모든 엣지 가운데 가중치가 최소 (1)인 (h,g)를 union 하게 됩니다. 해당 부분에는 cycle이 형성되어있지 않기 때문에 연결을 하게 되고, 가중치를 합산합니다.

(b)를 보게되면, 간선의 크기가 2번째인 (i,c)를 연결하게 됩니다.

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

(c)에서 간선의 크기가 (2)인 값을 계속해서 연결하게 됩니다. 연결되는 와중에는 union-find를 활용하여 같은 그룹으로 연결되어있는지를 체크합니다. 즉, cycle여부를 체크하게 됩니다.

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

계속해서 연결을 하다가, (f)의 그립을 보게되면, 간선의 크기가 (6)인값을 연결을 수행하였고, (i,g,f,c)가 같은 그룹으로 연결되어 싸이클을 형성하게 되기때문에, 간선 (i,g)값의 연결을 포기하고 다음으로 넘어가게 됩니다.

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

위와 같은 방식으로 연결을 계속해서 수행하게 되면, (n)같은 그림이 도출이 됩니다.

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

모든 정점의 노드가 간선으로 연결이 되어있고, 싸이클을 형성하지 않으면서 동시에 가장 최소의 간선합산으로 연결이 되어있습니다. 이것이 바로 MST이면서 동시에 크루스칼 알고리즘입니다 .

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

<a class="wp-editor-md-post-content-link" href="https://www.acmicpc.net/problem/1197" target="_blank" rel="noopener">최소 스패닝 트리</a>

가장 기본적인 MST 문제인거 같습니다.

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

public class MST_1197 {
    static Vector<kruscal> edge;
    static int n,m; // 3, 3
    static int res;
    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());
        n = Integer.parseInt(st.nextToken());
        m = Integer.parseInt(st.nextToken());
        parent = new int[n+1];
        for (int i = 1; i <= n; i++)
            parent[i] = i;

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

        Collections.sort(edge, 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;
                }
        });

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

        //2. 실제 작업.
        for (int i = 0; i < m; i++) {
            merge(edge.get(i).from, edge.get(i).to);
            if(chk)
                res += edge.get(i).val;
        }
        System.out.println(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>

중요한것은, vector안에 정점들의 값(from, to , val)순서로 넣고 value에 따라서 정렬을 수행합니다. 그리고 이어서 정점들을 하나씩 merge하되, 함수안에 내용을 보면 chk라는 같은 정점이면 거짓을 다른 정점이면 참으로 셋팅을 하도록 했습니다.

그래서 다른정점에 대한 간선값만 합산을 수행해서 최종적으로 res값을 출력해주는 문제입니다.

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

이번에는 최소 스패닝 트리에 대해서 알아보았습니다. 최소 스패닝 트리에는 크루스칼 외에도 프림 알고리즘이 있습니다. 이부분을 정리하기 위해서는 다익스트라에 대한 정리를 먼저 한 뒤, 이번 포스팅을 업데이트 하는 순서로 진행을 하고자 합니다.

다음시간에는 알고리즘에서 필수항목인 자료구조에 대해서 정리를 해보도록 하겠습니다.
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2020/12/07/segment-tree/">[Algorithms] 세그먼트 트리</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/11/16/minimum-spanning-tree/">[Algorithms] 최소 스패닝 트리(Minimum Spanning Tree)</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/16/minimum-spanning-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1571</post-id>	</item>
	</channel>
</rss>
