Luogu5123 [USACO18DEC]Cowpatibility
Luogu5123 [USACO18DEC]Cowpatibility
有 \(n\) 个物品,每个物品有 \(5\) 个属性,求有多少对物品交集为 \(\varnothing\)
\(n\leq5\times10^4,\ a_{i,\ j}\leq10^6\)
考虑原题的逆问题,即求有多少对物品交集非空
考虑容斥,如果一个大小为奇数的集合出现了 \(s\) 次,它的贡献为 \(\frac{s(s-1)}{2}\)
如果一个大小为偶数的集合出现了 \(s\) 次,它的贡献为 \(-\frac{s(s-1)}{2}\)
最终答案即为 \(\frac{n(n-1)}{2}-\) 贡献
现在的问题即为快速求出每种物品属性的子集在其它物品中出现的次数
可以用 map+vector 或者 map+hash
时间复杂度 \(O(32n\log n)\)
代码
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long u64;
const int maxn = 5e4 + 10;
int n;
#define iter map <u64, int> :: iterator
map <u64, int> cnt[2];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int a[5];
for (int j = 0; j < 5; j++) {
scanf("%d", a + j);
}
sort(a, a + 5);
for (int S = 1; S < 32; S++) {
u64 s = 0; int c = 0;
for (int j = 0; j < 5; j++) {
if (S >> j & 1) s = s * 998244353 + a[j], c++;
}
cnt[c & 1][s]++;
}
}
u64 ans = 0;
for (pair <u64, int> p : cnt[1]) {
int s = p.second;
ans += 1ll * s * (s - 1) / 2;
}
for (pair <u64, int> p : cnt[0]) {
int s = p.second;
ans -= 1ll * s * (s - 1) / 2;
}
printf("%lld", 1ll * n * (n - 1) / 2 - ans);
return 0;
}