이 영역을 누르면 첫 페이지로 이동
Arc 블로그의 첫 페이지로 이동

Arc

페이지 맨 위로 올라가기

Arc

[Algorithm] 프림 알고리즘(Prim's algorithm)

  • 2023.02.28 15:47
  • Algorithm/Algorithm
글 작성자: SeoArc

프림 알고리즘(Prim's algorithm)?

프림 알고리즘은 임의의 정점부터 시작하여 해당 정점에 연결된 가장 작은 가중치의 간선을 선택하며 확장해나가서 최소 신장 트리를 만드는 알고리즘이다.

 

구현

  1. 탐색을 시작할 임의의 정점을 하나 선택한다.
  2. 선택한 정점과 인접하는 정점 중 최소 비용의 간선을 갖는 정점을 선택한다.
  3. 모든 정점이 선택될 때 까지(n-1 개의 간선을 가질 때 까지) 반복한다.

 

동작 과정

 

코드

다음 코드는 baekjoon: 1197 - 최소 스패닝 트리를 기준으로 작성하였다.

 

1197번: 최소 스패닝 트리

첫째 줄에 정점의 개수 V(1 ≤ V ≤ 10,000)와 간선의 개수 E(1 ≤ E ≤ 100,000)가 주어진다. 다음 E개의 줄에는 각 간선에 대한 정보를 나타내는 세 정수 A, B, C가 주어진다. 이는 A번 정점과 B번 정점이

www.acmicpc.net

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Prim {

    static class Edge {
        int vertex;
        int weight;

        public Edge(int vertex, int weight) {
            this.vertex = vertex;
            this.weight = weight;
        }

        public int getVertex() {
            return vertex;
        }

        public int getWeight() {
            return weight;
        }
    }

    private static List<List<Edge>> graph;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] ve = br.readLine().split(" ");
        int v = Integer.parseInt(ve[0]); // 정점의 개수
        int e = Integer.parseInt(ve[1]); // 간선의 개수
        graph = new ArrayList<>();
        for (int i = 0; i <= v; i++) {
            graph.add(new ArrayList<>());
        }

        for (int i = 0; i < e; i++) {
            String[] input = br.readLine().split(" ");
            int vertex1 = Integer.parseInt(input[0]);
            int vertex2 = Integer.parseInt(input[1]);
            int weight = Integer.parseInt(input[2]);
            graph.get(vertex1).add(new Edge(vertex2, weight));
            graph.get(vertex2).add(new Edge(vertex1, weight));
        }

        System.out.println(search(1, v));
    }

    public static int search(int start, int n) {
        boolean[] visited = new boolean[n + 1];
        Queue<Edge> pq = new PriorityQueue<>(Comparator.comparingInt(Edge::getWeight));
        pq.offer(new Edge(start, 0));

        int total = 0;
        while (!pq.isEmpty()) {
            Edge edge = pq.poll();
            int vertex = edge.getVertex();
            int weight = edge.getWeight();

            if (visited[vertex]) {
                continue;
            }

            visited[vertex] = true;
            total += weight;

            for (Edge e : graph.get(vertex)) {
                if (!visited[e.vertex]) {
                    pq.add(e);
                }
            }
        }
        return total;
    }
}

'Algorithm > Algorithm' 카테고리의 다른 글

[Algorithm] 모듈러 산술(modular Arithmetic)  (0) 2023.03.09
[Algorithm] 위상 정렬(Topological Sort)  (0) 2023.03.07
[Algorithm] 다익스트라(Dijkstra)  (0) 2023.02.26
[Algorithm] 크루스칼 알고리즘 (Kruskal Algorithm)  (0) 2023.02.19
[Algorithm] 유니온-파인드(Union-Find)  (0) 2023.02.19

댓글

이 글 공유하기

  • 구독하기

    구독하기

  • 카카오톡

    카카오톡

  • 라인

    라인

  • 트위터

    트위터

  • Facebook

    Facebook

  • 카카오스토리

    카카오스토리

  • 밴드

    밴드

  • 네이버 블로그

    네이버 블로그

  • Pocket

    Pocket

  • Evernote

    Evernote

다른 글

  • [Algorithm] 모듈러 산술(modular Arithmetic)

    [Algorithm] 모듈러 산술(modular Arithmetic)

    2023.03.09
  • [Algorithm] 위상 정렬(Topological Sort)

    [Algorithm] 위상 정렬(Topological Sort)

    2023.03.07
  • [Algorithm] 다익스트라(Dijkstra)

    [Algorithm] 다익스트라(Dijkstra)

    2023.02.26
  • [Algorithm] 크루스칼 알고리즘 (Kruskal Algorithm)

    [Algorithm] 크루스칼 알고리즘 (Kruskal Algorithm)

    2023.02.19
다른 글 더 둘러보기

정보

Arc 블로그의 첫 페이지로 이동

Arc

  • Arc의 첫 페이지로 이동

검색

메뉴

  • 홈
  • 태그
  • 방명록

카테고리

  • 분류 전체보기 (106)
    • Language (28)
      • C++ (0)
      • C# (0)
      • Java (28)
    • Algorithm (47)
      • Algorithm (15)
      • Data Structure (6)
      • PS (26)
    • Computer Science (22)
      • Design Pattern (1)
      • Network (14)
      • OS (7)
    • Game (0)
      • Unity (0)
    • Backend (3)
      • Spring (1)
      • JPA (2)
    • DB (0)
      • SQL (0)
    • DevOps (2)
      • AWS (0)
      • Docker (2)
      • Jenkins (0)
      • Nginx (0)
    • Software Engineering (4)
      • OOP (4)
    • AI (0)
      • Machine Learning (0)
    • Others (0)

최근 글

인기 글

댓글

공지사항

아카이브

태그

  • 자바
  • 알고리즘
  • graph
  • algorithm
  • 그래프
  • network
  • 네트워크
  • java

나의 외부 링크

정보

SeoArc의 Arc

Arc

SeoArc

블로그 구독하기

  • 구독하기
  • RSS 피드

방문자

  • 전체 방문자
  • 오늘
  • 어제

티스토리

  • 티스토리 홈
  • 이 블로그 관리하기
  • 글쓰기
Powered by Tistory / Kakao. © SeoArc. Designed by Fraccino.

티스토리툴바