summaryrefslogtreecommitdiff
path: root/test/graph/kruskal.cpp
blob: bc1cce5fa5bf4bda63197cf8f05073e2c804f9f3 (plain)
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
#include "../util.h"
#include <datastructures/unionFind.cpp>

#define Edge Edge_ // we have a struct named Edge in util.h

struct Edge {
	int from, to;
	ll cost;
	bool operator<(const Edge& o) const {
		return cost > o.cost;
	}
};

#include <graph/kruskal.cpp>

ll prim(vector<Edge>& edges, int n) {
	vector<vector<pair<ll, int>>> adj(n);
	for (auto [a, b, d] : edges) {
		adj[a].emplace_back(d, b);
		adj[b].emplace_back(d, a);
	}
	priority_queue<pair<ll, int>> todo;
	vector<bool> seen(n);
	ll res = 0;
	for (ll i = 0; i < n; i++) {
		if (seen[i]) continue;
		todo.push({0, i});
		while (!todo.empty()) {
			auto [d, c] = todo.top();
			todo.pop();
			if (seen[c]) continue;
			seen[c] = true;
			res += d;
			for (auto e : adj[c]) {
				todo.push(e);
			}
		}
	}
	return res;
}

void stress_test() {
	ll queries = 0;
	for (int tries = 0; tries < 100'000; tries++) {
		int n = Random::integer<int>(2, 30);
		int m = Random::integer<int>(0, max<int>(n, min<int>(500, n*(n-1) / 2 + 1)));


		Graph<NoData> g(n);
		g.erdosRenyi(m);
		vector<Edge> edges;
		g.forEdges([&](int a, int b){
			ll w = Random::integer<ll>(-1'000'000'000ll, 1'000'000'000ll);
			edges.push_back({a, b, w});
		});

		vector<Edge> mst;
		ll got = kruskal(n, edges, mst);
		ll expected = prim(edges, n);

		if (got != expected) cerr << "got: " << got << ", expected: " << expected << FAIL;
		queries += n;
	}
	cerr << "tested random queries: " << queries << endl;
}

constexpr int N = 500'000;
constexpr int M = 3'000'000;
void performance_test() {
	timer t;
	Graph<NoData> g(N);
	g.erdosRenyi(M);
	vector<Edge> edges;
	g.forEdges([&](int a, int b){
		ll w = Random::integer<ll>(-1'000'000'000ll, 1'000'000'000ll);
		edges.push_back({a, b, w});
	});

	t.start();
	vector<Edge> mst;
	hash_t hash = kruskal(N, edges, mst);
	t.stop();
	if (t.time > 1000) cerr << "too slow: " << t.time << FAIL;
	cerr << "tested performance: " << t.time << "ms (hash: " << hash << ")" << endl;
}

int main() {
	stress_test();
	performance_test();
}