-
[백준]1922: 네트워크 연결문제풀이/백준 2021. 2. 16. 16:52
[백준]1922: 네트워크 연결
풀이
어제 MST를 공부한 기념으로 MST문제를 풀어보았다!
MST는 prim알고리즘과 kruskal알고리즘으로 풀 수 있다. 두 알고리즘을 모두 사용하여 문제를 풀어보았다.
이번 문제는 변형 1도 없이 MST알고리즘만 쓰면 답이 나온다!
코드
- prim algorithmn
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465import java.util.*;public class Main {static boolean[] visited;static int min = 0;static ArrayList<Node>[] list;public static void main(String[] args) {Scanner scan = new Scanner(System.in);int n = scan.nextInt();int m = scan.nextInt();list = new ArrayList[n + 1];for(int i = 1; i < n + 1; i++) {list[i] = new ArrayList<>();}for(int i = 0; i < m; i++) {int s = scan.nextInt();int e = scan.nextInt();int cost = scan.nextInt();list[s].add(new Node(e, cost));list[e].add(new Node(s, cost));}visited = new boolean[n + 1];prim();System.out.println(min);}public static void prim() {PriorityQueue<Node> q = new PriorityQueue<>();q.offer(new Node(1, 0));while(!q.isEmpty()) {Node current = q.poll();if(visited[current.x] == false) visited[current.x] = true;else continue;min += current.cost;for(int i = 0; i < list[current.x].size(); i++) {Node next = list[current.x].get(i);q.offer(next);}}}public static class Node implements Comparable<Node>{int x;int cost;public Node(int x, int cost) {this.x = x;this.cost = cost;}@Overridepublic int compareTo(Node n) {return this.cost - n.cost;}}}cs - kruskal algorithmn
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import java.util.*;public class Main {static boolean[] visited;static int min = 0;static int[] parent;static PriorityQueue<Node> q;static int n, m;public static void main(String[] args) {Scanner scan = new Scanner(System.in);n = scan.nextInt();m = scan.nextInt();q = new PriorityQueue<>();for(int i = 0; i < m; i++) {int s = scan.nextInt();int e = scan.nextInt();int cost = scan.nextInt();q.add(new Node(s, e, cost));}parent = new int[n + 1];kruskal();System.out.println(min);}public static void kruskal() {for(int i = 1; i <= n; i++) {parent[i] = i;}while(!q.isEmpty()) {Node node = q.poll();int p1 = find(node.s);int p2 = find(node.e);if(p1 != p2) {union(p1, p2);min += node.cost;}}}public static void union(int a, int b) {parent[a] = b;}public static int find(int a) {if(parent[a] == a) return a;else return parent[a] = find(parent[a]);}public static class Node implements Comparable<Node>{int s;int e;int cost;public Node(int s, int e, int cost) {this.s = s;this.e = e;this.cost = cost;}@Overridepublic int compareTo(Node n) {return this.cost - n.cost;}}}cs '문제풀이 > 백준' 카테고리의 다른 글
[백준]11404: 플로이드 - JAVA (0) 2021.02.17 [백준]2887: 행성 터널 - JAVA (0) 2021.02.16 [백준]1766: 문제집 - JAVA (0) 2021.02.15 [백준]10026: 적록색약 - JAVA (0) 2021.02.14 [백준]1939: 중량제한 - JAVA (0) 2021.02.14