洛谷 P1316 Mivik 写书(求关注、点赞)

代码

#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 写书 - 洛谷

求点赞、关注、收藏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值