首页 > 代码库 > 2014 BNU 邀请赛E题(递推+矩阵快速幂)

2014 BNU 邀请赛E题(递推+矩阵快速幂)

Elegant String

题意:给定一个字符串,由0-k数字组成,要求该串中,子串不包含0-k全排列的方案数
思路:dp[i][j]表示放到i个数字,后面有j个不相同,然后想递推式,大概就是对应每种情况k分别能由那几种状态转移过来,在纸上画画就能构造出矩阵了,由于n很大,所以用快速幂解决
代码:

#include <stdio.h>
#include <string.h>

const long long MOD = 20140518;

int t;
long long n;
int k;

struct Mat {
    long long v[10][10];
    Mat() {memset(v, 0, sizeof(v));}
    Mat operator * (Mat c) {
    Mat ans;
    for (int i = 0; i <= k; i++) {
        for (int j = 0; j <= k; j++) {
        for (int x = 0; x <= k; x++) {
            ans.v[i][j] = (ans.v[i][j] + v[i][x] * c.v[x][j]) % MOD;
        }
        }
    }
    return ans;
    }
} m;

Mat pow_mod(Mat a, long long k) {
    if (k <= 1) return a;
    Mat ans = pow_mod(a * a, k / 2);
    if (k & 1) ans = ans * a;
    return ans;
}

int main() {
    int cas = 0;
    scanf("%d", &t);
    while (t--) {
    scanf("%lld%d", &n, &k);
    memset(m.v, 0, sizeof(m.v));
    for (int i = 0; i < k; i++) {
        if (i != 0) m.v[i][i - 1] = (k - i + 1);
        for (int j = i; j < k; j++)
        m.v[i][j] = 1;
    }
    Mat c = pow_mod(m, n - 1);
    long long ans = 0;
    if (n == 1) ans = k + 1;
    else {
        for (int i = 0; i < k; i++)
        ans = (ans + (k + 1) * c.v[i][0]) % MOD;
    }
    printf("Case #%d: %lld\n", ++cas, ans);
    }
    return 0;
}