题目链接:点我
题目
Read the program below carefully then answer the question.
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include<iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include<vector>
const int MAX=100000*2;
const int INF=1e9;
int main()
{
int n,m,ans,i;
while(scanf("%d%d",&n,&m)!=EOF)
{
ans=0;
for(i=1;i<=n;i++)
{
if(i&1)ans=(ans*2+1)%m;
else ans=ans*2%m;
}
printf("%d\n",ans);
}
return 0;
}
Input
Multi test cases,each line will contain two integers n and m. Process to end of file.
[Technical Specification]
1<=n, m <= 1000000000
Output
For each case,output an integer,represents the output of above program.
Sample Input
1 10
3 100
Sample Output
1
5
题意:
就是题上代码的循环里的表达式那样,让你求最后的值.
思路:
我们分析一下那个递推公式: f[n] = f[n-1] * 2 + 1 ,n 是奇数, f[n] = f[n-1] * 2 , n 是偶数,那么我们假设n是奇数,于是f[n] = f[n-1] * 2 + 1, 由于 n 是奇数, 那么n - 1 必定是偶数, 于是继续递推得到, f[n] = f[n-1] + f[n-2] * 2 + 1, 于是我们发现这个公式对于任意的 n 都成立, 那么剩下的就是构造一个矩阵, 然后快速幂就可以了.根据递推公式,构造的矩阵为:
$
\begin{pmatrix}
f[n]\
f[n-1]\
1
\end{pmatrix}
$ = * $
\begin{pmatrix}
f[n-1]\
f[n-2]\
1 \
\end{pmatrix}
$
代码:
1 |
|