UVA - 10870 Recurrences

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


const int maxd = 100 + 4;
int d, n, m;
typedef long long Matrix[maxd][maxd];
typedef long long Vector[maxd];
Vector a, f;


//务必秉承不修改原变量的思想。因此开辟t这个辅助空间。
//因为有可能R和A都是指向同一块内存的两个指针,如果修改了R,则也修改了A,将导致错误。
void matrix_mul(Matrix A, Matrix B, Matrix R)
{
    Matrix t;
    memset(t, 0, sizeof(t));
    for(int i = 0; i < d; i++){
        for(int j = 0; j < d; j++){
            for(int k = 0; k < d; k++){
                t[i][j] = (t[i][j] + A[i][k]*B[k][j]) % m;
            }
        }
    }
    memcpy(R, t, sizeof(t));
}

void matrix_pow(Matrix A, int n, Matrix R)
{
    Matrix a, r;
    //cout << sizeof(a) << ' ' << sizeof(A) << endl;
    memcpy(a, A, sizeof(a));
    memset(r, 0, sizeof(r));
    for(int i = 0; i < d; i++)
        r[i][i] = 1;
    while(n){
        if(n&1){
            matrix_mul(r, a, r);
        }
        n >>= 1;
        matrix_mul(a, a, a);
    }
    memcpy(R, r, sizeof(r));
}


void matrix_mul_vector(Matrix A, Vector V, Vector R)
{
    Vector v;
    memset(v, 0, sizeof(v));
    for(int i = 0; i < d; i++){
        for(int j = 0; j < d; j++)
            v[i] = (v[i] + A[i][j]*V[j]) % m;
    }
    memcpy(R, v, sizeof(v));
}


int main()
{
    while(cin >> d >> n >> m && d){
        for(int i = 0; i < d; i++) cin >> a[i];
        for(int i = 0; i < d; i++) cin >> f[i];

        Matrix A;
        memset(A, 0, sizeof(A));
        for(int i = 0; i < d; i++){
            A[d-1][i] = a[d-i-1];
            if(i != 0)
                A[i-1][i] = 1;
        }
        matrix_pow(A, n - d, A);
        matrix_mul_vector(A, f, f);
        cout << f[d-1] << endl;
    }
    return 0;
}
/*
3 3 3
1 2 1
2 3 1
1 2 3
*/

 

上一篇:UVA - 10003 Cutting Sticks


下一篇:【转】花开正当时,十四款120/128GB SSD横向评测