-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkruskal.cpp
More file actions
86 lines (72 loc) · 2.25 KB
/
kruskal.cpp
File metadata and controls
86 lines (72 loc) · 2.25 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
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
#include "gen.h"
#include <cstdio>
#include <algorithm>
#include <tuple>
#include <vector>
#include <numeric>
using namespace std;
struct BiEdge {
vid_t from, to;
weight_t w;
bool operator<(const BiEdge& o) const {
return w < o.w;
}
} *biedges;
eid_t biEdgesCount;
struct {
vid_t *cmp;
void init(vid_t n) {
cmp = static_cast<vid_t*>(malloc(sizeof(vid_t) * n));
iota(cmp, cmp + n, 0);
}
vid_t get(vid_t v) {
return cmp[v] == v ? v : cmp[v] = get(cmp[v]);
}
void merge(vid_t v, vid_t u) {
//if (rand()&1) swap(v, u);
cmp[v] = u;
}
} snm;
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s input\n", argv[0]);
return 1;
}
int64_t timeRead = -currentNanoTime();
readAll(argv[1]);
timeRead += currentNanoTime();
int64_t timeInit = -currentNanoTime();
biedges = static_cast<BiEdge*>(malloc(sizeof(BiEdge) * edgesCount));
for (vid_t v = 0; v < vertexCount; ++v) {
for (eid_t i = edgesIds[v]; i < edgesIds[v + 1]; ++i) {
const vid_t u = edges[i].dest;
if (u <= v) continue;
const weight_t w = edges[i].weight;
biedges[biEdgesCount++] = BiEdge{v, u, w};
}
}
timeInit += currentNanoTime();
int64_t timeSort = -currentNanoTime();
sort(biedges, biedges + biEdgesCount);
timeSort += currentNanoTime();
int64_t timeBuild = -currentNanoTime();
weight_t result = 0.0;
snm.init(vertexCount);
for (eid_t e = 0; e < biEdgesCount; ++e) {
const int cv = snm.get(biedges[e].from);
const int cu = snm.get(biedges[e].to);
if (cv != cu) {
result += biedges[e].w;
snm.merge(cv, cu);
}
}
timeBuild += currentNanoTime();
printf("%.10lf\n", double(result));
fprintf(stderr, "Read time: %.5lf\n", double(timeRead) / 1e9);
fprintf(stderr, "Init time: %.5lf\n", double(timeInit) / 1e9);
fprintf(stderr, "Sort time: %.5lf\n", double(timeSort) / 1e9);
fprintf(stderr, "Bild time: %.5lf\n", double(timeBuild) / 1e9);
fprintf(stderr, "\n");
fprintf(stderr, "%.3lf\n%.3lf\n", double(timeRead + timeInit) / 1e9, double(timeSort + timeBuild) / 1e9);
return 0;
}