Yet another Number Sequence UVA

Yet another Number Sequence UVA

题目链接

题意:求斐波那契第n项,只不过是最后m位。

思路:矩阵快速幂板子

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N=52;
int mod=1000;
struct Matrix
{
    int n, m, g[N][N];
    Matrix(int _n, int _m)
    {
        n = _n;
        m = _m;
        for(int i=0;i<=n;i++)
        {
            for(int j=0;j<=m;j++)
            {
                g[i][j]=0;
            }
        }
    }
 
    // 矩阵相乘
    Matrix operator * (const Matrix& y)
    {
        Matrix z(n, y.m);
 
        for(int i=0; i<n; i++)
            for(int j=0; j<y.m; j++)
                for(int k=0; k<m; k++){
                int tmp=(long long )g[i][k]*y.g[k][j]%mod;
                z.g[i][j]=(z.g[i][j]+tmp)%mod;
            }
 
        return z;
    }
};
 
// 矩阵模幂
Matrix Matrix_Powmul(Matrix x, int m)
{
    Matrix z(x.n, x.n);
    for(int i=0; i<x.n; i++)
        z.g[i][i] = 1;
    while(m) {
        if(m & 1)
            z = z * x;
        x = x * x;
        m >>= 1;
    }
 
    return z;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int a,b,n,m;
        scanf("%d%d%d%d",&a,&b,&n,&m);
        mod=pow(10,m);
        if(n==0)
        {
            printf("%d
",a%mod);
        }
        else
        {
            Matrix tt=Matrix(2,2);
            tt.g[0][0]=1;
            tt.g[0][1]=1;
            tt.g[1][0]=1;
            tt.g[1][1]=0;
            tt=Matrix_Powmul(tt,n-1);
            Matrix ans1=Matrix(1,2);
            ans1.g[0][0]=b;
            ans1.g[0][1]=a;
            Matrix ans=ans1*tt;
            printf("%d
",ans.g[0][0]);
        }
     } 
    
}