P1316 Mivik 写书 题解
此处食用效果更佳
前情提要
洛谷 P1316
标准题解实在是过于复杂,但是这道题可以用容斥来做。由于很少做容斥的题,题解看了一个下午才看懂,于是便准备讲一个更清楚的(新手向,如十分累赘,请大佬勿喷)。
题目分析
总的情况数已知,这道题实际上相当于求解每个字符串的不同子串的个数和。
那么这道题为什么能用容斥呢?我们考虑一个确定的字符串,长度为 再次学习小学奥数访问 oi wiki。
但是一个一个枚举子串是不可能的,我们发现,有一些子串性质是一样的。就比如一种出现方式在很多子串中都有贡献,那此时我们就有了新的思路,我们先枚举子串的长度
那么有多少种子串能像这样的格式重复出现呢?我们发现在文章中这样的子串可能会有重叠,于是我们使用一个并查集来维护子串中每一位是否应该与另一位上的字符相同,相同的就连在一起了,统计一个子串中能自由选择的有
代码
#include <bits/stdc++.h>
#define mod 1000000007ll
using namespace std;
using ll = long long;
int n;
ll m;
ll qp(ll x, ll y) {
ll ans = 1;
while (y) {
if (y & 1) ans = ans * x % mod;
y >>= 1;
x = x * x % mod;
}
return ans;
}
ll ans;
int fa[25];
int getfa(int x) {
return x == fa[x] ? x : fa[x] = getfa(fa[x]);
}
void sol(int x) {
int a = (1 << (n - x + 1)), b = (1 << x) - 1; //a 是枚举出现位置,b 相当于一个掩膜
for (int i = 1; i < a; ++i) {
int c = 0, tot = 0;
for (int j = 0; j < x; ++j) fa[j] = j;
for (int j = 0; j < n; ++j) {
c = (c << 1) | ((i >> j) & 1); //存储最近 x 位的情况
c &= b;
if (!c) {
++tot; //没有被其它字符串覆盖
} else {
int t = c - (c & -c), tmp = getfa(__builtin_ctz(c)); //合并应该相同的字符
while (t) {
fa[getfa(__builtin_ctz(t))] = tmp;
t -= t & -t;
}
}
}
for (int j = 0; j < x; ++j) tot += (j == fa[j]); //加上不同的数量
ll tmp = qp(m, tot);
if (__builtin_parity(i)) { //出现奇数次加,偶数次减,容斥
ans = (ans + tmp) % mod;
} else {
ans = (ans - tmp + mod) % mod;
}
}
}
int main() {
scanf("%d%lld", &n, &m);
for (int i = 1; i <= n; ++i) sol(i);
printf("%lld", ans * qp(qp(m, n), mod - 2) % mod); //最后除以总的方案数就是期望
return 0;
}
后记
这个容斥应该算是很经典的,非常适合像我一样的组合蒟蒻食用。