跳到正文

个人记录

Some Bitset Tricks

Eric112约 3 分钟
原文
文章信息与版本

文章信息

发布
2024年10月29日
收录
2025年12月18日
更新
2026年11月16日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

rt

压位 floyd

在面对图的连通性或传递闭包之类的问题时,我们可以用 floyd 解决,时间复杂度 O(n3)O(n ^ 3),但用 bitset 可以优化到 O(n364)O(\frac {n ^ 3}{64}),已经可以过许多题了。

例题:P4306 [JSOI2010] 连通数

C++
#include <bits/stdc++.h>
#define debug cout << "CCF\n";
#define int long long
using namespace std;
const int maxn = 2005, mod = 1e9 + 7, base = 131;
char x;
int n, ans;
bitset<maxn> f[maxn];
main(){
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	cin >> n;
	for (int i = 1; i <= n; i++){
		for (int j = 1; j <= n; j++){
			cin >> x; if (x == '1') f[i][j] = 1;
		}f[i][i] = 1;
	}
	for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (f[j][i]) f[j] |= f[i];
	for (int i = 1; i <= n; i++) ans += f[i].count();
	cout << ans;
}

一定要记得 jj 在前,ii 在后!

bitset 优化背包

例题:[AGC020C] Median Sum

C++
#include <bits/stdc++.h>
#define debug cout << "CCF\n";
//#define int long long
using namespace std;
const int maxn = 4e6 + 5, mod = 1e9 + 7, base = 131;
int n, a[maxn], sum;
bitset<maxn> f;
main(){
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	cin >> n; f[0] = 1; for (int i = 1, x; i <= n; i++) cin >> x, f |= (f << x), sum += x;
	for (int i = sum + 1 >> 1; i <= sum; i++) if (f[i]) cout << i, exit(0);
}

关键在于 f∣(f<<x)f | (f << x),这代表着 ff 要么不取,要么原来所有可取到的值都加 xx。

原文