So Easy! - HUD 4565 递推→矩阵快速幂

133 篇文章 0 订阅
32 篇文章 0 订阅

So Easy!

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2089    Accepted Submission(s): 646


Problem Description
  A sequence S n is defined as:

Where a, b, n, m are positive integers.┌x┐is the ceil of x. For example, ┌3.14┐=4. You are to calculate S n.
  You, a top coder, say: So easy! 
 

Input
  There are several test cases, each test case in one line contains four positive integers: a, b, n, m. Where 0< a, m < 2 15, (a-1) 2< b < a 2, 0 < b, n < 2 31.The input will finish with the end of file.
 

Output
  For each the case, output an integer S n.
 

Sample Input
  
  
2 3 1 2013 2 3 2 2013 2 2 1 2013
 

Sample Output
  
  
4 14 4

思路:所有的n次方我们都可以把它看成是a[n]+b[n]*根号b,然而a[n+1]=a*a[n]+b*b[n],b[n+1]=a[n]+a*b[b]。所以我们可以写出一个矩阵  a   b    然后通过矩阵的相乘可以得到n次方式     a[n]   5*b[n]。

                               1  a                                                                      b[n]  a[n]

    然后根据数论,因为由a和b的关系可以得到,这个答案应该是2*a。

AC代码如下:

#include<cstdio>
#include<cstring>
using namespace std;
struct node
{ long long mat[2][2];
};
node mat[4];
long long a,b,n,m,ans;
int b2[100],len;
void mul(int p)
{ int i,j,k;
  memset(mat[3].mat,0,sizeof(mat[3].mat));
  for(i=0;i<=1;i++)
   for(j=0;j<=1;j++)
    for(k=0;k<=1;k++)
     mat[3].mat[i][j]=(mat[3].mat[i][j]+mat[1].mat[i][k]*mat[p].mat[k][j])%m;
  for(i=0;i<=1;i++)
   for(j=0;j<=1;j++)
    mat[1].mat[i][j]=mat[3].mat[i][j];
}
void solve()
{ len=0;
  memset(b2,0,sizeof(b2));
  while(n)
  { len++;
    if(n%2==1)
     b2[len]=1;
    n/=2;
  }
  while(--len)
  { if(b2[len]==0)
     mul(1);
    else
    { mul(1);
      mul(2);
    }
  }
}
int main()
{ int i,j,k;
  while(~scanf("%I64d%I64d%I64d%I64d",&a,&b,&n,&m))
  { mat[1].mat[0][0]=mat[2].mat[0][0]=a;
    mat[1].mat[0][1]=mat[2].mat[0][1]=b;
    mat[1].mat[1][0]=mat[2].mat[1][0]=1;
    mat[1].mat[1][1]=mat[2].mat[1][1]=a;
    solve();
    ans=mat[1].mat[0][0]*2%m;
    printf("%I64d\n",ans);
  }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值