题解:CF176B Word Cut

· · 题解

本题解设串长为 n,操作次数为 m。

此题具有神秘的特殊性质。

考虑对串 abcde 模拟,我们发现可能产生的结果只有 abcde bcdea cdeab deabc eabcd 五种。也就是说对于长度为 n 字符串 s,它进行若干次操作后的结果 t,总有一个整数 k\in[0,n),使得 s_i=t_{(i+k)\bmod n}。

于是我们可以枚举 k,检查第二个串是否为第一个串的操作结果。对于每个合法的 k,设 i 为操作次数,可以写出答案的转移方程 f_{i,k}=\sum\limits_{j\ne k}f_{i-1,j},因为每次操作我们可以至多偏移 n-1 个位置。

但是你发现这个方程转移起来是 O(nm) 的,应该怎么办?可以发现 f_{1,i}=\begin{cases}0&i=1\\1&i\ne1\end{cases},于是显然有 f_{i,j}=\begin{cases}(n-1)f_{i-1,2}&j=1\\f_{i-1,1}+(n-2)f_{i-1,2}&j\ne1\end{cases},将 2\sim n 的状态压缩起来用矩阵快速幂优化即可。

注意特判 m=0 时的情况,时间复杂度 O(n^2+\log m)。

#include <cstring>
#include <iostream>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
struct Matrix {
    ll a[2][2];
    ll operator()(ll x, ll y) const { return a[x][y]; }
    ll &operator()(ll x, ll y) { return a[x][y]; }
} f, g;
Matrix operator*(const Matrix &x, const Matrix &y) {
    Matrix z;
    z(0, 0) = (x(0, 0) * y(0, 0) % mod + x(0, 1) * y(1, 0) % mod) % mod;
    z(1, 0) = (x(1, 0) * y(0, 0) % mod + x(1, 1) * y(1, 0) % mod) % mod;
    z(0, 1) = (x(0, 0) * y(0, 1) % mod + x(0, 1) * y(1, 1) % mod) % mod;
    z(1, 1) = (x(1, 0) * y(0, 1) % mod + x(1, 1) * y(1, 1) % mod) % mod;
    return z;
}
Matrix qpow(Matrix x, ll y) {
    Matrix z;
    z(0, 0) = z(1, 1) = 1;
    z(0, 1) = z(1, 0) = 0;
    while (y) {
        if (y & 1)
            z = z * x;
        x = x * x;
        y >>= 1;
    }
    return z;
}
const ll N = 1000 + 5;
ll n, m, ans = 0;
char s[N], t[N];
int main() {
    f(1, 0) = f(1, 1) = 0;
    f(0, 0) = 0, f(0, 1) = 1;
    cin >> s >> t >> m;
    if (m == 0) {
        if (strcmp(s, t) == 0)
            cout << 1;
        else
            cout << 0;
        return 0;
    }
    n = strlen(s);
    g(0, 0) = 0;
    g(1, 1) = n - 2;
    g(0, 1) = 1;
    g(1, 0) = n - 1;
    f = f * qpow(g, m - 1);
    for (ll i = 0; i < n; i++) {
        bool ok = true;
        for (ll j = 0; j < n; j++)
            if (s[j] != t[(i + j) % n]) {
                ok = false;
                break;
            }
        if (!ok)
            continue;
        ans = (ans + f(0, i == 0 ? 0 : 1)) % mod;
    }
    cout << ans;
    return 0;
}