看到
K
K
只有 ,想 (cai) 到容斥。
即
26
2
6
枚举要求哪些泉区的泉水流量对应相同,那么就可以分别计算出答案后利用容斥原理得出最终答案了。
设现在枚举到泉水流量对应相同的泉区集合
S={...}
S
=
{
.
.
.
}
,怎么求泉区集合为
S
S
时合法的年份对数呢?
当然是用 万能的 Hash!啦!
对于每个年份,对泉区集合 的泉水流量设一个哈希函数,然后把哈希值相同的年份放在一起处理即得答案。
但上面是错的,正确的处理还需要乘以一个组合数
CK|S|
C
|
S
|
K
。
Q:为什么呢?
A:题目要求的是「恰好有
K
K
个」,在容斥的过程中,我们排除的情况是对应相等的年份不止 个的方案数,而实质上还是求其中有
K
K
个泉区相等的而不是 个泉区相等。而上面的做法求出的是有
|S|
|
S
|
个泉区相等的对数,所以还需要乘上
CK|S|
C
|
S
|
K
,相当于枚举哪
K
K
<script type="math/tex" id="MathJax-Element-31">K</script> 个泉区对应。
代码:
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read() {
int res = 0; bool bo = 0; char c;
while (((c = getchar()) < '0' || c > '9') && c != '-');
if (c == '-') bo = 1; else res = c - 48;
while ((c = getchar()) >= '0' && c <= '9')
res = (res << 3) + (res << 1) + (c - 48);
return bo ? ~res + 1 : res;
}
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e5 + 5, MI = 1234567, MX = 999979;
int n, K, a[N][7], ecnt, nxt[N], adj[MX], cnt[N], C[7][7];
bool sel[7]; ll ans; ull has[N], go[N];
void ins(ull x) {
int u = x % MX; for (int e = adj[u]; e; e = nxt[e])
if (go[e] == x) return (void) (cnt[e]++);
nxt[++ecnt] = adj[u]; adj[u] = ecnt; go[ecnt] = x; cnt[ecnt] = 1;
}
void check() {
int i, j, cc = 0; for (i = 1; i <= 6; i++) if (sel[i]) cc++;
if (cc < K) return; for (i = 1; i <= n; i++) {
has[i] = 0; for (j = 1; j <= 6; j++) if (sel[j])
has[i] = has[i] * MI + a[i][j]; ins(has[i]);
}
ll delta = 0; for (i = 1; i <= ecnt; i++)
delta += 1ll * (cnt[i] - 1) * cnt[i] >> 1; delta *= C[cc][K];
ecnt = 0; for (i = 1; i <= n; i++) adj[has[i] % MX] = 0;
if (cc - K & 1) ans -= delta; else ans += delta;
}
void dfs(int dep) {
if (dep == 7) return check();
sel[dep] = 0; dfs(dep + 1);
sel[dep] = 1; dfs(dep + 1);
}
int main() {
int i, j; n = read(); K = read();
for (i = 1; i <= n; i++) for (j = 1; j <= 6; j++) a[i][j] = read();
for (i = 0; i <= 6; i++) C[i][0] = 1;
for (i = 1; i <= 6; i++) for (j = 1; j <= i; j++)
C[i][j] = C[i - 1][j] + C[i - 1][j - 1];
dfs(1); cout << ans << endl;
return 0;
}