summaryrefslogtreecommitdiff
path: root/test/graph/cycleCounting.cpp
blob: 9c7bf0c589c2ae0b26e6e5483bf4491056fffc0a (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
#include "../util.h"
#include <datastructures/unionFind.cpp>
#include <graph/cycleCounting.cpp>

int naive(const vector<pair<int, int>>& edges, int n) {
	int res = 0;
	for (int i = 1; i < (1ll << ssize(edges)); i++) {
		vector<int> deg(n);
		init(n);
		int cycles = 0;
		for (int j = 0; j < ssize(edges); j++) {
			if (((i >> j) & 1) != 0) {
				auto [a, b] = edges[j];
				deg[a]++;
				deg[b]++;
				if (findSet(a) != findSet(b)) {
					unionSets(a, b);
				} else {
					cycles++;
				}
			}
		}
		bool ok = cycles == 1;
		for (auto d : deg) ok &= d == 0 || d == 2;
		if (ok) res++;
	}
	return res;
}

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

		Graph<NoData, 0, 1, 1> g(n);
		g.erdosRenyi(m);
		vector<pair<int, int>> edges;
		cycles cyc(n);
		g.forEdges([&](int a, int b){
			edges.emplace_back(a, b);
			cyc.addEdge(a, b);
		});

		int expected = naive(edges, n);
		int got = cyc.count();

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

constexpr int N = 100;
constexpr int M = 20;
void performance_test() {
	timer t;

	Graph<NoData> g(N);
	g.tree();
	g.erdosRenyi(M);
	cycles cyc(N);
	g.forEdges([&](int a, int b){
		cyc.addEdge(a, b);
	});

	t.start();
	hash_t hash = cyc.count();
	cerr << ssize(cyc.base) << endl;
	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();
}