矩阵的快速幂
sn 1 1 0 0 sn-1
fn+1 = 0 3 2 7* fn
fn 0 1 0 0 fn-1
fn-1 0 0 1 0 fn-2
#include <iostream>
#include <string.h>
using namespace std;
int n;
struct M{
    int t[4][4];
    M(){
        memset(t,0,sizeof(t));
    }
    void init(){
        t[0][0]=t[0][1]=t[2][1]=t[3][2]=1;
        t[1][1]=3;
        t[1][2]=2;
        t[1][3]=7;
    }
    void E(){
        for(int i=0;i<4;i++){
            t[i][i]=1;
        }
    }
};
M multiply(M a,M b){
    M c;
    for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
            for(int k=0;k<4;k++){
                c.t[i][j]=(c.t[i][j]+a.t[i][k]*b.t[k][j])%2009;
            }
        }
    }
    return c;
}
M powM(M a,int k){
    M tem;
    tem.E();
    while(k){
        if(k&1)tem=multiply(a,tem);
        a=multiply(a,a);
        k>>=1;
    }
    return tem;
}
int main(){
    int t;
    cin>>t;
    M a,b,c;
    a.t[0][0]=4;
    a.t[1][0]=5;
    a.t[2][0]=3;
    a.t[3][0]=1;
    b.init();
    for(int i=1;i<=t;i++){
        cin>>n;
        cout<<"Case "<<i<<": ";
        if(n==0)cout<<"1\n";
        else {
            c=powM(b,n-1);
            c=multiply(c,a);
            cout<<c.t[0][0]<<endl;
        }
    }
    return 0;
}
原文地址:http://www.cnblogs.com/Mr-Xu-JH/p/3857484.html