您的位置:首页 > 其它

hdu 4565(矩阵快速幂)

2016-06-07 13:20 357 查看


So Easy!

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 3675    Accepted Submission(s): 1194

Problem Description

  A sequence Sn 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 Sn.

  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 < 215, (a-1)2< b < a2, 0 < b, n < 231.The input will finish with the end of file.

 

Output

  For each the case, output an integer Sn.

 

Sample Input

2 3 1 2013
2 3 2 2013
2 2 1 2013

 

Sample Output

4
14
4

 

Source

2013
ACM-ICPC长沙赛区全国邀请赛——题目重现

#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll Mod;

struct Matrix
{
ll ma[2][2];
void init(ll a,ll b,ll c,ll d){
ma[0][0]=a;ma[0][1]=b;
ma[1][0]=c;ma[1][1]=d;
}
Matrix(){
memset(ma,0,sizeof(ma));
}
Matrix operator * (const Matrix &m){
Matrix res;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
res.ma[i][j]=(res.ma[i][j]+m.ma[i][k]*ma[k][j])%Mod;
return res;
}
};

Matrix quick_powm(Matrix m,ll n)
{
if(n==1)return m;
Matrix res=quick_powm(m,n/2);
Matrix ans=res*res;
if(n%2==1)
ans=ans*m;
return ans;
}

int main()
{
ll a,b,n;
while(~scanf("%lld%lld%lld%lld",&a,&b,&n,&Mod))
{
Matrix m,res;
m.init(a,1,b,a);
res=quick_powm(m,n);
printf("%lld\n",(2*res.ma[0][0])%Mod);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: