rt
压位 floyd
在面对图的连通性或传递闭包之类的问题时,我们可以用 floyd 解决,时间复杂度 ,但用 bitset 可以优化到 ,已经可以过许多题了。
#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;
}一定要记得 在前, 在后!
bitset 优化背包
#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);
}
关键在于 ,这代表着 要么不取,要么原来所有可取到的值都加 。