forked from carlfriess/MinSpantree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminSpantree.c
70 lines (54 loc) · 1.66 KB
/
minSpantree.c
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
#include <stdio.h>
#include <stdlib.h>
struct Vertex {
int value;
struct Vertex *parent;
};
struct Vertex* getRoot(struct Vertex *node) {
return node->parent == node ? node : getRoot(node->parent);
}
struct Edge {
struct Vertex *u;
struct Vertex *v;
int weight;
};
int edgeCompare(const void * a, const void * b) {
return ( (*(struct Edge*)a).weight - (*(struct Edge*)b).weight );
}
int main(int argc, const char * argv[]) {
int test;
scanf("%d", &test);
for (; test > 0; test--) {
int numVertices;
scanf("%d", &numVertices);
int numEdges;
scanf("%d", &numEdges);
struct Vertex vertices[numVertices];
struct Edge edges[numEdges];
for (int i = 0; i < numVertices; i++) {
vertices[i].value = i;
vertices[i].parent = &vertices[i];
}
for (int i = 0; i < numEdges; i++) {
int uValue;
scanf("%d", &uValue);
uValue--;
int vValue;
scanf("%d", &vValue);
vValue--;
edges[i].u = &vertices[uValue];
edges[i].v = &vertices[vValue];
scanf("%d", &edges[i].weight);
}
qsort(edges, numEdges, sizeof(edges[0]), edgeCompare);
int totalWeight = 0;
for (int i = 0; i < numEdges; i++) {
if (getRoot(edges[i].u) != getRoot(edges[i].v)) {
getRoot(edges[i].v)->parent = getRoot(edges[i].u);
totalWeight += edges[i].weight;
}
}
printf("%d\n", totalWeight);
}
return 0;
}