summaryrefslogtreecommitdiff
path: root/test/graph/centroid.cpp
blob: 633c3f172400d93f7f2a4a940e182699db999508 (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
#include "../util.h"
vector<vector<int>> adj;
#include <graph/centroid.cpp>

int subtreeSize(int c, int p) {
	int res = 1;
	for (int x : adj[c]) {
		if (x == p) continue;
		res += subtreeSize(x, c);
	}
	return res;
}

vector<int> naive() {
	vector<int> res;
	for (int i = 0; i < ssize(adj); i++) {
		bool isCentroid = true;
		for (int j : adj[i]) isCentroid &= 2*subtreeSize(j, i) <= ssize(adj);
		if (isCentroid) res.push_back(i);
	}
	return res;
}

void stress_test() {
	ll queries = 0;
	for (int tries = 0; tries < 100'000; tries++) {
		int n = Random::integer<int>(1, 50);
		Graph<NoData> g(n);
		g.tree();

		adj.assign(n, {});
		g.forEdges([&](int a, int b){
			adj[a].push_back(b);
			adj[b].push_back(a);
		});

		auto expected = naive();
		ranges::sort(expected);

		for (int i = 0; i < n; i++) {
			auto [a, b] = find_centroid(i);
			vector<int> got;
			if (a >= 0) got.push_back(a);
			if (b >= 0) got.push_back(b);
			ranges::sort(got);

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

constexpr int N = 2'000'000;
void performance_test() {
	timer t;
	Graph<NoData> g(N);
	g.tree();

	adj.assign(N, {});
	g.forEdges([&](int a, int b){
		adj[a].push_back(b);
		adj[b].push_back(a);
	});

	t.start();
	auto [gotA, gotB] = find_centroid();
	t.stop();
	hash_t hash = gotA + gotB;
	if (t.time > 500) cerr << "too slow: " << t.time << FAIL;
	cerr << "tested performance: " << t.time << "ms (hash: " << hash << ")" << endl;
}

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