bzoj 2326 矩阵快速幂

思路:矩阵快速幂搞一搞。

#include<bits/stdc++.h>
#define LL long long
#define fi first
#define se second
#define mk make_pair
#define PII pair<int, int>
#define PLI pair<LL, int>
#define ull unsigned long long
using namespace std;

const int N = 3e5 + 7;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int Mod = 1e9 + 7;

LL n;
int mod;

struct Matrix {
    int a[3][3];
    Matrix() {
        memset(a, 0, sizeof(a));
    }
    void init() {
        for(int i = 0; i < 3; i++)
            a[i][i] = 1;
    }
    Matrix operator * (const Matrix &B) const {
        Matrix C;
        for(int i = 0; i < 3; i++)
            for(int j = 0; j < 3; j++)
                for(int k = 0; k < 3; k++)
                    C.a[i][j] = (C.a[i][j] + 1ll * a[i][k] * B.a[k][j]) % mod;
        return C;
    }
    Matrix operator ^ (LL b) {
        Matrix C; C.init();
        Matrix A = (*this);
        while(b) {
            if(b & 1) C = C * A;
            A = A * A; b >>= 1;
        }
        return C;
    }
} M;

int main() {
    int Mat[3][3] = {
        {1, 1, 0},
        {0, 1, 1},
        {0, 0, 1}
    };
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 3; j++)
            M.a[i][j] = Mat[i][j];

    scanf("%lld%d", &n, &mod);

    Matrix A; A.init();
    bool flag = true;
    for(LL i = 1000000000000000000; i; i /= 10) {
        LL p = 0;
        if(n >= i) {
            if(flag) p = n - i + 1;
            else p = i * 10 - i;
            flag = false;
        }
        M.a[0][0] = i % mod * 10 % mod;
        A = A * (M ^ p);
    }
    printf("%d\n", (A.a[0][1] + A.a[0][2]) % mod);
    return 0;
}

/*
*/

 

posted @ 2018-09-28 18:59  NotNight  阅读(124)  评论(0编辑  收藏  举报