题意
题解
考虑枚举一个出现多次的字符串,不断把出现多次的重复子串容斥掉。
首先枚举字符串长度 ,然后枚举这个字符串的出现位置集合 满足 。显然该集合对答案的贡献系数为 。
考虑用并查集维护在集合枚举下必须相同的位置,枚举每一个位置,把所有的串的每一个位置映射到 上,将应该相同的位置做并查集合并。计算当前 的位置或者没有被映射为位置个数 ,则答案为 ,再乘上当前的容斥系数即可。
讲的有些抽象,细节见代码,有注释。
Code
// Problem: P1316
#include <bits/stdc++.h>
#define int long long
#define ll long long
#define F(i, a, b) for (int i = (a); i <= (b); ++i)
#define D(i, a, b) for (int i = (a); i >= (b); --i)
using namespace std;
inline ll rd() {
ll x = 0; bool f = 1; char ch = getchar();
while (ch < '0' || ch > '9') { if (ch == '-') f = 0; ch = getchar(); }
while (ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return (f ? x : (-x));
}
const int mod = 1e9 + 7, N = 25;
int n, m, fa[N], ans, col[N];
int qpow(int x, int k) {
int res = 1;
while (k) {
if (k & 1) res = res * x % mod;
x = x * x % mod, k >>= 1;
}
return res;
}
int Find(int x) { return (x == fa[x] ? x : fa[x] = Find(fa[x])); }
signed main() {
n = rd(), m = rd();
F(len, 1, n) { // 枚举长度 len
F(i, 0, (1<<(n-len+1))-1) { // 枚举起始位置集合 i
int popc = __builtin_popcount(i);
if (!popc) continue; // 没出现则对答案没有贡献
memset(col, -1, sizeof col);
F(j, 0, len) fa[j] = j;
F(j, 0, n-len) if (i>>j & 1) {
F(k, 0, len-1) { // 把所有的串的每一个位置映射到 [0, len) 上
if (col[j + k] == -1) col[j + k] = k; // 对应的位置
else fa[Find(k)] = Find(col[j + k]); // 应该相同的位置合并
}
}
int cur = 0; // 统计自由选择位置个数 cur
F(j, 0, len-1) if (fa[j] == j) ++cur;
F(j, 0, n-1) if (col[j] == -1) ++cur;
cur = qpow(m, cur); // 转换成答案形式
if (popc & 1) ans = (ans + cur) % mod;
else ans = (ans - cur + mod) % mod;
}
}
ans = ans * qpow(qpow(m, n), mod - 2) % mod;
cout << ans << '\n';
return 0;
}