codevs1574广义斐波那契数列

1574 广义斐波那契数列

 

 时间限制: 1 s
 空间限制: 256000 KB
 题目等级 : 钻石 Diamond
 
 
题目描述 Description

广义的斐波那契数列是指形如an=p*an-1+q*an-2的数列。今给定数列的两系数p和q,以及数列的最前两项a1和a2,另给出两个整数n和m,试求数列的第n项an除以m的余数。

输入描述 Input Description

输入包含一行6个整数。依次是p,q,a1,a2,n,m,其中在p,q,a1,a2整数范围内,n和m在长整数范围内。

输出描述 Output Description

输出包含一行一个整数,即an除以m的余数。

样例输入 Sample Input

1 1 1 1 10 7

样例输出 Sample Output

6

/*
矩阵乘法模板
跟斐波那契差不多
就是初始化难理解
静下心来推推式子,然后明确a1,a2是最后才乘上的就好了 
*/
#include<iostream>
#include<cstdio>
#define ll long long

using namespace std;
int n,mod,q,p,a1,a2;
struct node
{
    ll m[2][2];
}ans,base;

ll init()
{
    ll x=0,f=1;char c=getchar();
    while(c>'9'||c<'0'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return f*x;
}

node mul(node a,node b)
{
    node tmp;
    for(int i=0;i<2;i++)
      for(int j=0;j<2;j++)
      {
         tmp.m[i][j]=0;
         for(int k=0;k<2;k++)
           tmp.m[i][j]=(tmp.m[i][j]+a.m[i][k]*b.m[k][j])%mod;
      }
      return tmp;
}

void qw(ll n)
{
    while(n)
    {
        if(n&1) ans=mul(ans,base);
        base=mul(base,base);n>>=1;
    }
}

int main()
{
    p=init();q=init();
    a1=init();a2=init();
    n=init();mod=init();
    ans.m[0][0]=0;ans.m[0][1]=q;
    ans.m[1][0]=1;ans.m[1][1]=p;
    base.m[0][0]=0;base.m[0][1]=q;
    base.m[1][0]=1;base.m[1][1]=p;
    n-=2;
    qw(n);
    
    printf("%lld
",(a1*ans.m[0][0]%mod+a2*ans.m[1][0]%mod)%mod);
    return 0;
}
数据范围及提示 Data Size & Hint

数列第10项是55,除以7的余数为6。

折花枝,恨花枝,准拟花开人共卮,开时人去时。 怕相思,已相思,轮到相思没处辞,眉间露一丝。
原文地址:https://www.cnblogs.com/L-Memory/p/6366308.html