Reading comprehension
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1548 Accepted Submission(s): 618
Problem Description
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;
}
#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
[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
Source
Recommend
题意:按照题目中给的程序,给定n和m,n为执行次数,奇数时执行(2*ans+1)%m,偶数次时执行2*ans%m,求最后结果。
思路:数据范围很大,直接做肯定T,看到模就想到了快速幂,写下前几个数找找规律就构造出了一个矩阵。按照模板敲完一直WA,百思不得其解,然而最后发现矩阵tm应该开成long long啊你484傻,真心为智商跪了...
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
struct matrix{
long long m[3][3];
}E,A;
void init(){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
E.m[i][j]=(i==j);
}
}
}
matrix mul(matrix A,matrix B,int mod){
matrix ans;
memset(ans.m,0,sizeof(ans.m));
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
ans.m[i][j]=0;
for(int k=0;k<3;k++){
ans.m[i][j]+=(A.m[i][k]*B.m[k][j])%mod;
ans.m[i][j]%=mod;
}
}
}
return ans;
}
matrix quickmod(matrix A,int n,int mod){
matrix t=A,d=E;
while(n>0){
if(n&1)
d=mul(d,t,mod);
n>>=1;
t=mul(t,t,mod);
}
return d;
}
int main(){
int n,mod;
while(~scanf("%d %d",&n,&mod)){
init();
A.m[0][0]=1;A.m[0][1]=2;A.m[0][2]=1;
A.m[1][0]=1;A.m[1][1]=0;A.m[1][2]=0;
A.m[2][0]=0;A.m[2][1]=0;A.m[2][2]=1;
if(n==1)
printf("%d\n",1%mod);
if(n==2)
printf("%d\n",2%mod);
if(n>2){
matrix ans=quickmod(A,n-2,mod);
printf("%lld\n",(1LL*ans.m[0][0]*2+ans.m[0][1]+ans.m[0][2])%mod);
}
}
return 0;
}