So Easy!(题目链接)
思路:
AC Code:
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<map>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<list>
#define mod 10000
#define Max 0x3f3f3f3f
#define Min 0xc0c0c0c0
#define mst(a) memset(a,0,sizeof(a))
#define f(i,a,b) for(int i=a;i<b;i++)
using namespace std;
typedef long long ll;
const int MAX_N = 1e3 + 5;
ll a, b, n, m;
struct Matirx{
int r, c;
ll mat[2][2];
};
Matirx m1, m2, m3;
Matirx Mul(Matirx a, Matirx b){
Matirx c ;
c.r = a.r, c.c = b.c;
for(int i = 0; i < a.r; i++){
for(int j = 0; j < b.c; j++){
c.mat[i][j] = 0;
for(int t = 0; t < a.c; t++){
c.mat[i][j] += a.mat[i][t] * b.mat[t][j];
}
c.mat[i][j] %= m;
}
}
return c;
}
Matirx quick_pow(int n){
Matirx tmp = m2, res = m1;
while(n){
if(n & 1){
res = Mul(res, tmp);
}
tmp = Mul(tmp, tmp);
n >>= 1;
}
return res;
}
void init(){
m1.c = 2, m1.r = 2, m2.c = 2, m2.r = 2, m3.r = 2, m3.c = 1;
m1.mat[0][0] = 1, m1.mat[0][1] = 0, m1.mat[1][0] = 0, m1.mat[1][1] = 1;
m2.mat[0][0] = 0, m2.mat[0][1] = 1, m2.mat[1][0] = b - a * a, m2.mat[1][1] = 2 * a;
m3.mat[0][0] = 2 * a, m3.mat[1][0] = 2 * (a * a + b);
}
int main(){
//freopen("c1.txt", "r", stdin);
//freopen("c2.txt", "w", stdout);
while(scanf("%I64d%I64d%I64d%I64d", &a, &b, &n, &m) != EOF){
init();
if(n == 1){
cout<<(2 * a) % m<<endl;
}
else if(n == 2){
cout<<(2 * ( a * a + b) ) % m<<endl;
}
else {
Matirx res = quick_pow(n - 2);
m3 = Mul(res, m3);
cout<<(m3.mat[1][0] + m) % m<<endl;
}
}
//fclose(stdin);
//fclose(stdout);
return 0;
}