Reading comprehension
Time limit | 1000 ms |
---|---|
Memory limit | 32768 kB |
OS | Windows |
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
仔细阅读下面的程序,然后回答问题。
- 输入
多个测试用例,每行包含两个整数n和m。处理到文件结尾。
【技术规范】
1<=N,m<=100000000
- 输出
对于每种情况,输出一个整数,表示上述程序的输出。
样例输入输出如上。
先不考虑余m
可以直接看代码知道第奇数个ans是前一个的两倍加一,第偶数个ans是前一个的两倍
然后列个式子就能知道f(n) = f(n-1) + 2 * f(n-2) + 1
也可以直接复制代码跑一遍找下规律
最后输出f(n) % m
矩阵a
[
2
1
1
0
0
0
0
0
0
]
(4)
\begin{bmatrix} 2 & 1 & 1 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix} \tag{4}
⎣⎡200100100⎦⎤(4)
矩阵b
[
1
1
0
2
0
0
1
0
1
]
(4)
\begin{bmatrix} 1 & 1 & 0 \\ 2 & 0 & 0 \\ 1 & 0 & 1 \end{bmatrix} \tag{4}
⎣⎡121100001⎦⎤(4)
Time | 31ms |
---|---|
Memory | 1220kB |
Length | 1069 |
Lang | G++ |
#include <stdio.h>
#include <string.h>
using namespace std;
#define ll long long
struct matrix{
ll m[4][4];/*我习惯写矩阵下标从1到3,所以会多开一个*/
}a,b;
matrix multiply(matrix a, matrix b,int mod){
matrix temp;
memset(temp.m,0,sizeof(temp.m));
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
for (int k = 1; k <= 3; k++) {
temp.m[i][j] += a.m[i][k] * b.m[k][j];
temp.m[i][j] = temp.m[i][j] % mod;
}
}
}
return temp;
}
matrix power (matrix a, matrix b, int p, int mod){
while (p) {
if(p & 1) a = multiply(a, b, mod);
b = multiply(b, b, mod);
p = p >> 1;
}
return a;
}
int main(int argc, char const *argv[]) {
int n, m;
memset(a.m, 0, sizeof(a.m));
memset(b.m, 0, sizeof(b.m));
a.m[1][1] = 2; a.m[1][2] = 1; a.m[1][3] = 1;
b.m[1][1] = 1; b.m[1][2] = 1; b.m[2][1] = 2; b.m[3][1] = 1; b.m[3][3] = 1;
while(~scanf("%d %d", &n, &m)){
matrix end;
if(n <= 2){
printf("%lld\n", a.m[1][3-n] % m);/*注意前两个也要取余,我就因为这个WA了两发*/
continue;
}
end = power(a, b, n-2, m);
printf("%lld\n" , end.m[1][1] % m);
}
return 0;
}