-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKruskal.java
More file actions
51 lines (43 loc) · 1.27 KB
/
Kruskal.java
File metadata and controls
51 lines (43 loc) · 1.27 KB
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
import java.util.*;
public class Kruskal {
int vNum;
Graph graph;
Edge[]edges;
public Kruskal( Graph graph){
this.graph=graph;
this.vNum=graph.getN();
edges=graph.edges;
}
int runKruskal() {
DSF dsf = new DSF(vNum); // ÑÍÌ
//shellSort(edges);
Arrays.sort(edges); // Ñîðòèðóåì ðåáðà
// for (int i=0; i<edges.length; i++)
// System.out.println(edges[i].getInfo());
int ret = 0; // ðåçóëüòàò
for (Edge e : edges) // ïåðåáèðàåì ðåáðà â ïîðÿäêå âîçðàñòàíèÿ
if (dsf.union(e.u, e.v)) // åñëè ðåáðà ïðèíàäëåæàò ðàçíûì êîìïîíåíòàì
ret += e.w; // äîáàâëÿåì âåñ ðåáðà ê ñòîèìîñòè MST
return ret;
}
void shellSort(Edge[]edges)
{
int j;
int step = edges.length / 2;
while (step > 0)
{
for (int i = 0; i < (edges.length - step); i++)
{
j = i;
while ((j >= 0) && (edges[j].w > edges[j + step].w))
{
int tmp = edges[j].w;
edges[j].w = edges[j + step].w;
edges[j + step].w = tmp;
j-=step;
}
}
step = step / 2;
}
}
}