FZU 1683 纪念SlingShot

点击打开FZU1683

思路: 矩阵快速幂

分析:

1 题目给定f(n) = 3*f(n-1)+2*f(n-2)+7*f(n-3) , f(0) = 1 , f(1) = 3 , f(2) = 5 ,给定n求f(0)+...+f(n) %2009

2 矩阵快速幂的水题,我们构造出这样的矩阵,然后利用矩阵快速幂即可

   3 2 7 0      f(n-1)      f(n)

   1 0 0 0 *   f(n-2) =   f(n-1)

   0 1 0 0      f(n-3)      f(n-2)

   3 2 7 1      sum        sum'


代码:

/************************************************
 * By: chenguolin                               * 
 * Date: 2013-08-27                             *
 * Address: http://blog.csdn.net/chenguolinblog *
 ************************************************/
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

typedef __int64 int64;
const int MOD = 2009;
const int N = 4;

int64 n;
struct Matrix{
    int64 mat[N][N];
    Matrix operator*(const Matrix &m)const{
        Matrix tmp;
        for(int i = 0 ; i < N ; i++){
            for(int j = 0 ; j < N ; j++){
                tmp.mat[i][j] = 0;
                for(int k = 0 ; k < N ; k++)
                    tmp.mat[i][j] += mat[i][k]*m.mat[k][j]%MOD;
                tmp.mat[i][j] %= MOD;
            }
        }
        return tmp;
    }
};

void init(Matrix &m){
    memset(m.mat , 0 , sizeof(m.mat)); 
    m.mat[0][0] = m.mat[3][0] = 3;
    m.mat[0][1] = m.mat[3][1] = 2;
    m.mat[0][2] = m.mat[3][2] = 7;
    m.mat[1][0] = m.mat[3][3] = 1;
    m.mat[2][1] = 1;
}

int Pow(Matrix m){
    if(n == 0) return 1;
    if(n == 1) return 3;
    if(n == 2) return 5;
    n -= 2;
    Matrix ans;
    memset(ans.mat , 0 , sizeof(ans.mat));
    for(int i = 0 ; i < N ; i++)
        ans.mat[i][i] = 1;
    while(n){
        if(n%2)
            ans = ans*m;
        n /= 2;
        m = m*m;
    }
    int sum = 0;
    sum += ans.mat[3][0]*5%MOD;
    sum += ans.mat[3][1]*3%MOD;
    sum += ans.mat[3][2]*1%MOD;
    sum += ans.mat[3][3]*9%MOD;
    return sum%MOD;
}

int main(){
    int Case;
    int cas = 1;
    Matrix m;
    init(m);
    scanf("%d" , &Case);
    while(Case--){
        printf("Case %d: " , cas++);
        scanf("%I64d" , &n);
        printf("%d\n" , Pow(m));
    }
    return 0;
}


你可能感兴趣的:(FZU 1683 纪念SlingShot)