代码
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
using ll = long long;
int n;
ll m;
ll ans;
// Function to compute x^y % mod using exponentiation by squaring
ll power(ll x, ll y, ll mod) {
ll result = 1;
x = x % mod;
while (y > 0) {
if (y & 1) // If y is odd, multiply x with the result
result = (result * x) % mod;
y = y >> 1; // y = y / 2
x = (x * x) % mod; // Change x to x^2
}
return result;
}
// Function to find the representative of a set using path compression
int find(int x, int fa[]) {
return (x == fa[x]) ? x : (fa[x] = find(fa[x], fa));
}
// Function to solve for a given length of substring x
void solve(int x) {
int a = (1 << (n - x + 1)), b = (1 << x) - 1; // a is the enumeration of appearance positions, b acts as a mask
for (int i = 1; i < a; ++i) {
int c = 0, tot = 0;
int fa[25]; // Array to store union-find representatives, assuming max size is 25
for (int j = 0; j < x; ++j) fa[j] = j; // Initialize each character's representative to itself
for (int j = 0; j < n; ++j) {
c = (c << 1) | ((i >> j) & 1); // Store the recent x bits situation
c &= b; // Apply the mask b
if (!c) {
++tot; // Increment if not covered by other strings
} else {
int t = c - (c & -c), tmp = find(__builtin_ctz(c), fa); // Merge same characters
while (t) {
fa[find(__builtin_ctz(t), fa)] = tmp;
t -= t & -t;
}
}
}
for (int j = 0; j < x; ++j) tot += (j == find(j, fa)); // Add different amounts
ll tmp = power(m, tot, MOD);
if (__builtin_parity(i)) { // Odd add, even subtract, overlap
ans = (ans + tmp) % MOD;
} else {
ans = (ans - tmp + MOD) % MOD;
}
}
}
int main() {
scanf("%d%lld", &n, &m);
for (int i = 1; i <= n; ++i) solve(i);
printf("%lld", ans * power(power(m, n, MOD), MOD - 2, MOD) % MOD); // Finally divide by the total number of schemes is the expected value
return 0;
}
链接:Mivik 写书 - 洛谷
求点赞、关注、收藏