So Easy! HDU - 4565
A sequence S n is defined as:
Sn=⌈(a+b√)n⌉%m
S
n
=
⌈
(
a
+
b
)
n
⌉
%
m
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
题意:
求上面的公式
分析:
直接看这篇文章吧,照着这个题写的讲解
得到递推式
fn=2a⋅fn−1+(b−a2)⋅fn−2
f
n
=
2
a
⋅
f
n
−
1
+
(
b
−
a
2
)
⋅
f
n
−
2
打表发现这个递推式取模好像没有循环节因此只能老老实实用矩阵快速幂
(fnfn−1)=(2a1b−aa0)⋅(fn−1fn−2)(1)
(1)
(
f
n
f
n
−
1
)
=
(
2
a
b
−
a
a
1
0
)
⋅
(
f
n
−
1
f
n
−
2
)
(fnfn−1)=(2a1b−aa0)n−1⋅(f1f0)(2)
(2)
(
f
n
f
n
−
1
)
=
(
2
a
b
−
a
a
1
0
)
n
−
1
⋅
(
f
1
f
0
)
code:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5+10;
int a,b,n,m;
struct Matrix{
int mm[3][3];
};
Matrix mul(Matrix aa,Matrix bb){
Matrix ans;
for(int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++){
ans.mm[i][j] = 0;
for(int k = 0; k < 2; k++){
ans.mm[i][j] = (ans.mm[i][j] + aa.mm[i][k] * bb.mm[k][j] % m + m) % m;
}
}
}
return ans;
}
Matrix q_pow(Matrix aa,int bb){
Matrix ans;
memset(ans.mm,0,sizeof(ans.mm));
for(int i = 0; i < 2; i++){
ans.mm[i][i] = 1;
}
while(bb){
if(bb & 1)
ans = mul(ans,aa);
bb >>= 1;
aa = mul(aa,aa);
}
return ans;
}
int main(){
while(~scanf("%d%d%d%d",&a,&b,&n,&m)){
Matrix ans;
ans.mm[0][0] = 2 * a % m;
ans.mm[0][1] = b - a * a;
ans.mm[1][0] = 1;
ans.mm[1][1] = 0;
ans = q_pow(ans,n-1);
printf("%d\n",(ans.mm[0][0] * 2 * a % m + ans.mm[0][1] * 2 % m + m) % m);
}
return 0;
}
同类型题目Best Solver HDU - 5451
这道题取模有循环节,处理起来就相对简单些了