• FZU 1683


    矩阵的快速幂

    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 ";
            else {
                c=powM(b,n-1);
                c=multiply(c,a);
                cout<<c.t[0][0]<<endl;
            }

        }
        return 0;
    }

  • 相关阅读:
    Hibernate Tomcat JNDI数据源配置(转)
    使用Spring的@Autowired 实现DAO, Service, Controller三层的注入(转)
    丢弃重口味的xml配置--spring4用groovy配置bean(转)
    Java 对象的生命周期
    设计模式学习总结(23) 中介者模式
    WebSocket初探
    设计模式 之 建造者
    谈谈CListCtrl 扩展风格设置方法-SetExtendedStyle和ModifyStyleEx 比較
    linux signal 处理
    UVA 1546
  • 原文地址:https://www.cnblogs.com/Mr-Xu-JH/p/3857484.html
Copyright © 2020-2023  润新知