【题解】P1316 Mivik 写书

· · 题解

我认为出题人想麻烦了。

我们考虑计算一个串的答案,所有子串数是 \dfrac{n(n + 1)}{2},但是会存在一些本质相同的串被重复计算,所以我们考虑容斥使得每个本质相同的串只出现一次。

具体方法是枚举起点集合 S,其中 x\in S 表示原串的一个子串多次出现的左端点集合,然后长度相同的子串本质上是相同的,可以一起容斥。

时间复杂度是 \mathcal{O}(n^22^n),实际效率在 n=24 时只用 3s,感觉更像大常数的 n2^n,更准确的上界不会证明。

#define M 1050000
int n, m, ans, bt[M], mt[M], fa[26], pw[26];
int get(int x){return fa[x] == x ? x : fa[x] = get(fa[x]);}
void calc(int x){
    int s = n - x + 1, o = (1 << x) - 1, w = (1 << s) - 1;
    rp(i, w){
        int c = 0, k = 0;
        rep(j, 0, x - 1)fa[j] = j;
        rep(j, 0, n - 1){
            c = (c << 1) | (1 & (i >> j)), c &= o;
            if(c){
                int p = get(mt[c & -c]), t = c - (c & -c); 
                for(; t; t -= t & -t)fa[get(mt[t & -t])] = p;
            }
            else k++;
        }
        rep(j, 0, x - 1)k += fa[j] == j;
        if(bt[i])ad(ans, pw[k]);
        else su(ans, pw[k]);
    }
}
int main() {
    read(n, m);
    int w = (1 << n) - 1;
    rep(i, 0, n)mt[1 << i] = i;
    pw[0] = 1; rp(i, n)pw[i] = pw[i - 1] * 1LL * m % P;
    rp(i, w)bt[i] = (i & 1) ^ (bt[i >> 1]);
    rp(i, n)calc(i);
    int inv = Pow(m, P - 2);
    rp(i, n)ans = ans * 1LL * inv % P;
    printf("%d\n", ans);
    return 0;
}