Yet another Number Sequence UVA - 10689 (矩阵快速幂板题)

传送门

题意:给出a,b,n,m。f(0)=a,f(1)=b,求f(n)=f(n-1)+f(n-2)的最后m位数字。 
题解:矩阵的模板题。

附上代码:


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;

ll mod;

struct node{
    ll a[3][3];
};
node shu,ans,mp;

node matrix(node x,node y)
{
    for(int i=1;i<=2;i++){
        for(int j=1;j<=2;j++){
            mp.a[i][j]=0;
            for(int p=1;p<=2;p++){
                mp.a[i][j]=(mp.a[i][j]+x.a[i][p]*y.a[p][j]+mod)%mod;
            }
        }
    }
    return mp;
}

void work(ll k)
{
    for(int i=1;i<=2;i++){
        for(int j=1;j<=2;j++){
            ans.a[i][j]=0;
        }
    }
    for(int i=1;i<=2;i++){
        ans.a[i][i]=1;
    }
    node t=shu;
    while(k){
        if(k&1){
            ans=matrix(ans,t);
        }
        k>>=1;
        t=matrix(t,t);
    }
}

int main()
{
    int t;
    scanf("%d",&t);
    ll a,b,n,m;
    while(t--){
        scanf("%lld%lld%lld%lld",&a,&b,&n,&m);
        mod=1;
        while(m--){
            mod*=10;
        }
        memset(shu.a,0,sizeof(shu.a));
        shu.a[1][1]=shu.a[1][2]=shu.a[2][1]=1;
        node B;
        B.a[1][1]=b;
        B.a[2][1]=a;
        if(n==0){
            printf("%lld\n",a%mod);
        }else if(n==1){
            printf("%lld\n",b%mod);
        }else{
            work(n-1);
            B=matrix(ans,B);
            printf("%lld\n",B.a[1][1]%mod);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhouzi2018/article/details/81911827