一.题目链接
二.思路
思路参考:https://www.acwing.com/solution/content/25805/
三.代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 3;
int n, m;
void mul(int c[], int a[], int b[][N])
{
int temp[N] = {0};
//一维乘二维 先枚举列
for(int i = 0; i < N; i ++)
for(int k = 0; k < N; k ++)//自由变量
temp[i] = (temp[i] + (LL)a[k] * b[k][i]) % m;
memcpy(c, temp, sizeof temp);//将答案复制过来 此处只能sizeof temp, 不能用c 否则是返还指针的长度
}
void mul(int c[][N], int a[][N], int b[][N])
{
int temp[N][N] = {0};
//二维乘二维
for(int i = 0; i < N; i++)//枚举答案行
for(int j = 0; j < N; j ++)//枚举答案列
for(int k = 0; k < N; k ++)//自由变量
temp[i][j] = (temp[i][j] + (LL)a[i][k] * b[k][j]) % m;
memcpy(c, temp, sizeof temp);
}
int main()
{
cin >> n >> m;
// fn * A = fn+1
// fn = [fn fn+1 sn]
int f1[N] = {1, 1, 1};//起始值
int a[N][N] = {
{0, 1, 0},
{1, 1, 1},
{0, 0, 1}
};
n --;
while(n)
{
if(n & 1) mul(f1, f1, a);//res = res * a
mul(a, a, a);//a = a * a;
n >>= 1;
}
cout << f1[2] << endl;
return 0;
}