DP+矩阵快速幂 HDOJ 5318 The Goddess Of The Moon

 

题目传送门

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<ll> Vec;
typedef vector<Vec> Mat;
const int N = 55;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
int n, m;
int a[N];
int dp[N][N];

bool judge(int x, int y) {
    char p[15], q[15];
    sprintf(p, "%d", x);
    sprintf(q, "%d", y);
    int lenp = strlen(p), lenq = strlen(q);
    for (int i=0; i<lenp; ++i) {
        int k = 0;
        while (i + k < lenp && k < lenq && p[i+k] == q[k]) k++;
        if (i + k == lenp && k >= 2) return true;
    }
    return false;
}

void add_mod(ll &a, ll b) {
    a += b;
    if (a >= MOD) a -= MOD;
}
 
Mat matrix_mul(const Mat &A, const Mat &B) {
    Mat ret(A.size(), Vec(B[0].size()));
    for (int i=0; i<A.size(); ++i)
        for (int j=0; j<A[0].size(); ++j) if (A[i][j])
            for (int k=0; k<B[0].size(); ++k) if (B[j][k])
                add_mod(ret[i][k], A[i][j]*B[j][k]%MOD);
    return ret;
}
 
Mat matrix_pow(Mat X, int n) {
    Mat ret(X.size(), Vec(X.size()));
    for (int i=0; i<X.size(); ++i) ret[i][i] = 1;
    for (; n; n>>=1) {
        if (n & 1) ret = matrix_mul(ret, X);
        X = matrix_mul(X, X);
    }
    return ret;
}

Mat get_base()  {
    Mat ret(n, Vec(n));
    for (int i=0; i<n; ++i)    {
        for (int j=0; j<n; ++j)    {
            if (judge(a[i], a[j])) ret[i][j] = 1;
        }
    }
    return ret;
}

int main() {
    int T;
    scanf("%d", &T);
    while (T--) {
        scanf("%d%d", &n, &m);
        for (int i=0; i<n; ++i) {
            scanf("%d", &a[i]);
        }
        sort(a, a+n);
        n = unique(a, a+n)-a;
        Mat base = get_base();
        Mat res = matrix_pow(base, m-1);
        ll ans = 0;
        for (int i=0; i<n; ++i) {
            for (int j=0; j<n; ++j) {
                add_mod(ans, res[i][j]);
            }
        }
        printf("%lld\n", ans);
    }
    return 0;
}

  

posted @ 2015-07-31 19:34  Running_Time  阅读(179)  评论(0编辑  收藏  举报