From 679d4788d4e16c3fca7f0af9975518b5d1450848 Mon Sep 17 00:00:00 2001 From: setop Date: Thu, 26 Dec 2024 00:35:38 +0100 Subject: [PATCH] day 23, bron kerbosch is more efficient than me --- d23/part2_bron_kerbosch.py | 23 +++++++++++++++++++++++ d23/part2_naive.py | 1 - 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 d23/part2_bron_kerbosch.py diff --git a/d23/part2_bron_kerbosch.py b/d23/part2_bron_kerbosch.py new file mode 100644 index 0000000..4567de6 --- /dev/null +++ b/d23/part2_bron_kerbosch.py @@ -0,0 +1,23 @@ +from collections import defaultdict as DD +import sys + +G = DD(set) + +for line in sys.stdin.read().strip().split('\n'): + a, b = line.split('-') + G[a].add(b) + G[b].add(a) + +def bron_kerbosch(r, p, x): + if len(p) == 0 and len(x) == 0: + yield r + else: + pivot = max(p | x, key=lambda x: len(G[x])) + for v in p - G[pivot]: + neighbours = G[v] + yield from bron_kerbosch(r | {v}, p & neighbours, x & neighbours) + p.remove(v) + x.add(v) + +clique = max(bron_kerbosch(set(), set(G.keys()), set()), key=len) +print(','.join(sorted(clique))) diff --git a/d23/part2_naive.py b/d23/part2_naive.py index 6d7ad38..741d984 100644 --- a/d23/part2_naive.py +++ b/d23/part2_naive.py @@ -1,7 +1,6 @@ import sys from collections import defaultdict as DD - D = DD(set) S = set() for i in sys.stdin.read().strip().split('\n'):