티스토리 뷰
반응형
문제
- 도현이는 컴퓨터와 컴퓨터를 모두 연결하는 네트워크를 구축하려 한다. 하지만 아쉽게도 허브가 있지 않아 컴퓨터와 컴퓨터를 직접 연결하여야 한다.
- 그런데 모두가 자료를 공휴가 위해서는 모든 컴퓨터가 연결이 되어 있어야 한다. (a와 b가 연결이 되어 있다는 말은 a에서 b로의 경로가 존재한다는 것을 의미한다. a에서 b를 연결하는 선이 있고, b와 c를 연결하는 선이 있으면 a와 c는 연결이 되어 있다.)
- 이왕이면 컴퓨터를 연결하는 비용을 최소로 하여야 컴퓨터를 연결하는 비용 외에 다른 곳에 돈을 더 쓸 수 있을 것이다.
- 이제 각 컴퓨터를 연결하는데 필요한 비용이 주어졌을 때 모든 컴퓨터를 연결하는데 필요한 최소비용을 출력하라. 모든 컴퓨터를 연결할 수 없는 경우는 없다.
입력
- 첫째 줄에 컴퓨터의 수 N (1 ≤ N ≤ 1000) 가 주어진다.
- 둘째 줄에는 연결할 수 있는 선의 수 M (1 ≤ M ≤ 100,000) 가 주어진다.
- 셋째 줄부터 M + 2 번째 줄까지 총 M개의 줄에 각 컴퓨터를 연결하는데 드는 비용이 주어진다. 이 비용의 정보는 세 개의 정수로 주어지는데, 만약에 a b c 가 주어져 있다고 하면 a컴퓨터와 b컴퓨터를 연결하는데 비용이 c (1 ≤ c ≤ 10,000) 만큼 든다는 것을 의미한다.
출력
- 모든 컴퓨터를 연결하는데 필요한 최소비용을 첫째 줄에 출력한다.
솔루션
- 특별하게 고려할 것 없이 최소 스패닝 트리 알고리즘을 그대로 구현하면 된다.
Code
Kruskal 알고리즘
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
import java.util.*;
import java.io.*;
public class Solution_1922_2 {
static int V, E;
static Graph graph;
static int[] parent, rank;
public static void Swap(int n1, int n2) {
int temp = n1;
n1 = n2;
n2 = temp;
}
public static void Union(int u, int v) {
int uR = Find(u);
int vR = Find(v);
if (uR == vR)
return;
if (rank[uR] > rank[vR])
Swap(uR, vR);
parent[uR] = vR;
if (rank[uR] == rank[vR])
rank[vR]++;
}
public static int Find(int u) {
if (u == parent[u])
return u;
return parent[u] = Find(parent[u]);
}
public static int NetworkMST() {
int mincost = 0, idx = 0;
Collections.sort(graph.edge);
for (int i = 0; i < graph.edge.size(); i++) {
Edge edge = graph.edge.get(i);
if (Find(edge.from) != Find(edge.to)) {
Union(edge.from, edge.to);
mincost += edge.cost;
}
}
return mincost;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
V = Integer.parseInt(br.readLine());
E = Integer.parseInt(br.readLine());
graph = new Graph(V);
parent = new int[V + 1];
rank = new int[V + 1];
for (int i = 1; i <= V; i++)
parent[i] = i;
for (int i = 0; i < E; i++) {
st = new StringTokenizer(br.readLine());
int from = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
int cost = Integer.parseInt(st.nextToken());
graph.addEdge(from, to, cost);
}
bw.write(NetworkMST() + " ");
bw.flush();
bw.close();
br.close();
}
public static class Graph {
List<Edge> edge;
public Graph(int V) {
edge = new ArrayList<>();
}
public void addEdge(int from, int to, int cost) {
edge.add(new Edge(from, to, cost));
}
}
public static class Edge implements Comparable<Edge> {
int from, to, cost;
public Edge(int from, int to, int cost) {
this.from = from;
this.to = to;
this.cost = cost;
}
@Override
public int compareTo(Edge e) {
return this.cost - e.cost;
}
}
}
|
Prim 알고리즘
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
import java.util.*;
import java.io.*;
public class Solution_1922 {
static int V, E;
static Graph graph;
static boolean[] visited;
public static int NetworkMST(int start) {
PriorityQueue<Edge> pq = new PriorityQueue<>();
Queue<Integer> q = new LinkedList<>();
int mincost = 0;
q.offer(start);
while (!q.isEmpty()) {
int from = q.poll();
visited[from] = true;
for (Edge edge : graph.edge[from]) {
if (!visited[edge.to]) {
pq.offer(edge);
}
}
while (!pq.isEmpty()) {
Edge edge = pq.poll();
if (!visited[edge.to]) {
q.add(edge.to);
visited[edge.to] = true;
mincost += edge.cost;
break;
}
}
}
return mincost;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
V = Integer.parseInt(br.readLine());
E = Integer.parseInt(br.readLine());
visited = new boolean[V + 1];
graph = new Graph(V);
for (int i = 0; i < E; i++) {
st = new StringTokenizer(br.readLine());
int from = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
int cost = Integer.parseInt(st.nextToken());
graph.addEdge(from, to, cost);
}
bw.write(NetworkMST(1) + " ");
bw.flush();
bw.close();
br.close();
}
public static class Graph {
List<Edge>[] edge;
public Graph(int V) {
edge = new LinkedList[V + 1];
for (int i = 1; i <= V; i++)
edge[i] = new LinkedList<>();
}
public void addEdge(int from, int to, int cost) {
edge[from].add(new Edge(from, to, cost));
edge[to].add(new Edge(to, from, cost));
}
}
public static class Edge implements Comparable<Edge> {
int from, to, cost;
public Edge(int from, int to, int cost) {
this.from = from;
this.to = to;
this.cost = cost;
}
@Override
public int compareTo(Edge e) {
return this.cost - e.cost;
}
}
}
|
결과
반응형
'Algorithm > Solution' 카테고리의 다른 글
[백준 10282] - 해킹 (0) | 2019.12.11 |
---|---|
[백준 9372] - 상근이의 여행 (0) | 2019.12.10 |
[프로그래머스] - 오픈채팅방 (0) | 2019.12.08 |
[백준 1786] - 찾기 (0) | 2019.12.03 |
[프로그래머스] - 전화번호 목록 (0) | 2019.12.01 |
댓글