Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

Bron-Kerbosch 算法模板

求最大团。

记录方案使用了 bitset ,如果没有方案需求可以只记录 count() 。

查看代码
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
#include <cstdio>
#include <vector>
#define eb emplace_back
#include <bitset>
using namespace std;
template <class Type>
void read (Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 1) + (x << 3) + c - '0';
flag && (x = ~x + 1);
}
template <class Type, class ...rest>
void read (Type &x, rest &...y) { read(x), read(y...); }
template <class Type>
void write (Type x)
{
x < 0 && (putchar('-'), x = ~x + 1);
x > 9 && (write(x / 10), 0);
putchar('0' + x % 10);
}
const int N = 510;
int n, m, f[N];
bool g[N][N];
vector <int> st[N];
bitset <N> ans;
bool dfs (bitset <N> cur)
{
int k = cur.count(), sz = st[k].size();
if (!sz)
{
if (k > ans.count()) return ans = cur, true;
return false;
}
for (int i = 0; i < sz; i++)
{
int t = st[k][i];
if (min(sz - i + k, f[t] + k) <= ans.count()) return false;
st[k + 1].clear();
for (int j = i + 1; j < sz; j++)
if (g[t][st[k][j]]) st[k + 1].eb(st[k][j]);
cur.set(t); bool flag = dfs(cur); cur.reset(t);
if (flag) return true;
}
return false;
}
int main()
{
read(n, m);
for (int a, b; m; --m)
read(a, b), g[a][b] = g[b][a] = 1;
for (int i = n; i >= 1; i--)
{
st[1].clear();
for (int j = i + 1; j <= n; j++)
if (g[i][j]) st[1].eb(j);
bitset <N> t; t.set(i);
dfs(t);
f[i] = ans.count();
}
write(ans.count()), puts("");
for (int i = 1; i <= n; ++i)
if (ans[i]) write(i), putchar(' ');
return 0;
}