zoukankan      html  css  js  c++  java
  • hdu 4990 Reading comprehension (矩阵快速幂)

    题意:读程序,找规律

    思路:我们把程序输出发现序列为1,2,5,10,21,42,85,170,递推式f(n)=2*f(n-2)+f(n-1)+1

    代码:

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <cmath>
    #define ll long long
    
    using namespace std;
    
    const int N=3,M=3,P=3;
    ll mod;
    
    struct Matrix
    {
        ll m[N][N];
    };
    
    Matrix A={1,2,1,
              1,0,0,
              0,0,1};
    
    Matrix I={1,0,0,
              0,1,0,
              0,0,1};
    
    Matrix multi(Matrix a,Matrix b)
    {
        Matrix ans;
        for(int i=0;i<N;i++)
        {
            for(int j=0;j<M;j++)
            {
                ans.m[i][j]=0;
                for(int k=0;k<P;k++)
                {
                    ans.m[i][j]+=(a.m[i][k]*b.m[k][j])%mod;
                }
                ans.m[i][j]%=mod;
            }
        }
        return ans;
    }
    
    Matrix power(Matrix a,ll b)
    {
        Matrix ans=I;
        while(b)
        {
            if(b&1)
            {
                ans=multi(ans,a);
            }
            b=b/2;
            a=multi(a,a);
        }
        return ans;
    }
    
    int main()
    {
        ll n;
        while(cin>>n>>mod)
        {
            if(n==1)
            {
                cout<<(1)%mod<<endl;continue;
            }
            else if(n==2)
            {
                cout<<(2)%mod<<endl;
                continue;
            }
            Matrix ans=power(A,n-2);
            cout<<(ans.m[0][0]*2+ans.m[0][1]*1+ans.m[0][2])%mod<<endl;
        }
        return 0;
    }
  • 相关阅读:
    iOS基础
    iOS基础 ----- 内存管理
    NSAttributedString 的一些基本用法
    node安装使用
    docker常用命令
    docker lnmp
    easy-wechat
    composer
    center7系统搭建lnmp
    xammp环境配置
  • 原文地址:https://www.cnblogs.com/simplekinght/p/7087374.html
Copyright © 2011-2022 走看看