题目链接:HDU 4990 Reading comprehension
题目大意:
(f_0 = 0),(n)为奇数时:(f_n = f_{n-1} imes 2 + 1),(n)为偶数时:(f_n = f_{n-1} imes 2)。
已知(n)和(m),求(f_n\%m。)
题解:
假设(n)为奇数,那么(f_n=f_{n-1} imes 2+1),而(n-1)必定是偶数,所以有:(f_n=f_{n-1}+f_{n-2} imes 2+1);
同理,假设(n)为偶数,那么(f_n=f_{n-1} imes 2),而(n-1)必定是奇数,所以有:(f_n=f_{n-1}+f_{n-2} imes 2+1)。
那么,(f_n=f_{n-1}+f_{n-2} imes 2+1)对于任意(n(n>0))恒成立。
构造矩阵:
[left(egin{matrix}
f_i \
f_{i-1} \
1
end{matrix}
ight)
=
left(egin{matrix}
1 & 2 & 1 \
1 & 0 & 0 \
0 & 0 & 1
end{matrix}
ight)
imes
left(egin{matrix}
f_{i-1} \
f_{i-2} \
1
end{matrix}
ight)
]
所以:
[left(egin{matrix}
f_n \
f_{n-1} \
1
end{matrix}
ight)
=
left(egin{matrix}
1 & 2 & 1 \
1 & 0 & 0 \
0 & 0 & 1
end{matrix}
ight)^{n-1}
imes
left(egin{matrix}
f_1 \
f_0 \
1
end{matrix}
ight)
]
由(f_1 = 1,f_0 = 0)得:
[left(egin{matrix}
f_n \
f_{n-1} \
1
end{matrix}
ight)
=
left(egin{matrix}
1 & 2 & 1 \
1 & 0 & 0 \
0 & 0 & 1
end{matrix}
ight)^{n-1}
imes
left(egin{matrix}
1 \
0 \
1
end{matrix}
ight)
]
#include <iostream>
#include <cstring>
using namespace std;
struct Matrix { // 矩阵
int row, col;
long long num[3][3];
};
long long n, m;
Matrix multiply(Matrix a, Matrix b) { // 矩阵乘法
Matrix temp;
temp.row = a.row, temp.col = b.col;
memset(temp.num, 0, sizeof(temp.num));
for (int i = 0; i < a.row; ++i)
for (int j = 0; j < b.col; ++j)
for (int k = 0; k < a.col; ++k)
temp.num[i][j] = (temp.num[i][j] + a.num[i][k] * b.num[k][j] % m) % m;
return temp;
}
Matrix fastPow(Matrix base, long long k) { // 矩阵快速幂
Matrix ans;
ans.row = ans.col = 3;
memset(ans.num, 0, sizeof(ans.num));
ans.num[0][0] = ans.num[1][1] = ans.num[2][2] = 1;
while (k) {
if (k & 1) {
ans = multiply(ans, base);
}
base = multiply(base, base);
k >>= 1;
}
return ans;
}
int main() {
Matrix base;
base.row = base.col = 3;
base.num[0][0] = base.num[0][2] = base.num[1][0] = base.num[2][2] = 1;
base.num[1][1] = base.num[1][2] = base.num[2][0] = base.num[2][1] = 0;
base.num[0][1] = 2;
while (cin >> n >> m) {
Matrix ans = fastPow(base, n - 1);
cout << (ans.num[0][0] + ans.num[0][2]) % m << endl;
}
return 0;
}