长沙的邀请赛题目,题目难度和题目一样so easy 可是我还是没有自己做出来,也是因为没有认真想把。
这道题有两个方面的看点,一个是通过题目所给的条件推出公式就可以了
思路:留意数据范围(a-1)^2<b<a^2,可知0<a-√b<1,不难想到(a+√b)^n+(a-√b)^n的和为整数,而0<(a-√b)^n<1,所以Sn=[(a+√b)^n+(a-√b)^n]%m,
已知Sn的通项公式了,如果我们能求出它的递推公式,就能用矩阵乘法解决了。
易知特征根为r1=a+√b,r2=a-√b,所以特征方程为r^2-(r1+r2)r+r1*r2=0,即r^2-2a*r+(a^2-b)=0,
所以Sn的递推公式为Sn=2a*Sn-1+(b-a^2)*Sn-2。
然后就构造矩阵:
初始值S1=(a+√b)%m,S2=2*(a^2+b),于是这道题就变成矩阵乘法了。
矩阵快速幂也是第一次使用,其实一开始常数的快速幂是会的只是学完线代之后感觉矩阵快速幂好像还有矩阵内部的优化,不过看了网上的代码发现就和常数的一样的优化思路有点失望,不过明白过来之后就分分钟AC以后也不怕了~~
不多说上代码!
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <functional>
#include <cstdio>
#include <queue>
#include <map>
#include <algorithm>
#include <stack>
#include <utility>
typedef long long ll;
using namespace std;
const int mx = 10000;
ll x[2][2],y[2][2];
ll a,b,m,n;
void ML(ll av[2][2],ll bv[2][2])
{
ll ans[2][2];
int i,k,j;
memset(ans,0,sizeof(ans));
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
{
// printf("i = %d j = %d ans = %lld\n",i,j,ans[i][j]);
for(k = 0; k < 2; k++)
ans[i][j] = ((ans[i][j]+(av[i][k] * bv[k][j])%m)%m+m) % m;
// printf("i = %d j = %d ans = %lld\n",i,j,ans[i][j]);
}
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
av[i][j] = ans[i][j];
}
int main ()
{
int i,j,k,l;
ll an;
while(scanf("%lld%lld%lld%lld",&a,&b,&n,&m) != EOF)
{
x[0][0] = 2*a;
x[0][1] = b - a*a;
x[1][0] = 1;
x[1][1] = 0;
y[0][0] = 1;
y[1][0] = 0;
y[1][1] = 1;
y[0][1] = 0;
// printf("a = %lld b = %lld\n",a,b);
while(n)
{
// printf("n = %lld\n",n);
if(n&1)
ML(y,x);
ML(x,x);
n = n >> 1;
// printf("%lld %lld\n",y[0][0],y[1][0]);
}
an = (y[1][0] * 2 * a + y[1][1] * 2) % m;
an = (an + m) % m;
printf("%lld\n",an);
}
}