uva10870

https://vjudge.net/problem/UVA-10870

裸的矩阵快速幂 注意系数矩阵在前面 因为系数矩阵为d*d 方程矩阵为d * 1 放反了就是d * 1 d * d 不符合矩阵乘法

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 20;
struct mat {
    ll a[N][N];    
} x, g;
int n, m, d;
ll a[N], f[N];
mat operator * (mat a, mat b)
{
    mat ret; memset(ret.a, 0, sizeof(ret.a));
    for(int i = 1; i <= d; ++i)
        for(int j = 1; j <= d; ++j)
            for(int k = 1; k <= d; ++k) ret.a[i][j] = (ret.a[i][j] + a.a[i][k] % m * b.a[k][j] % m) % m;
    return ret;
}
void build()
{
    memset(x.a, 0, sizeof(x.a)); memset(g.a, 0, sizeof(g.a));
    for(int i = 1; i <= d; ++i) x.a[i][1] = f[d - i + 1];
    for(int i = 1; i <= d; ++i) g.a[1][i] = a[i];
    for(int i = 2; i <= d; ++i) g.a[i][i - 1] = 1;
}
mat power(mat A, int t)
{
    mat ret; memset(ret.a, 0, sizeof(ret.a));
    for(int i = 1; i <= d; ++i) ret.a[i][i] = 1;
    for(; t; t >>= 1, A = A * A) if(t & 1) ret = ret * A;    
    return ret;
}
int main()
{
    while(scanf("%d%d%d", &d, &n, &m))
    {
        if(n == 0 && d == 0 && m == 0) break;
        for(int i = 1; i <= d; ++i) scanf("%d", &a[i]), a[i] %= m;
        for(int i = 1; i <= d; ++i) scanf("%d", &f[i]), f[i] %= m;
        if(n <= d)
        {
            printf("%d\n", f[n]);
            continue;
        }
        build();
        mat t = power(g, n - d);
        t = t * x;
        printf("%lld\n", t.a[1][1]);
    }
    return 0;
}
View Code

 

posted @ 2017-04-28 16:25  19992147  阅读(118)  评论(0编辑  收藏  举报