Reading comprehension题解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Little_Small_Joze/article/details/79463804
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1286    Accepted Submission(s): 515


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;
}
 

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

AC C++(网上竟然暂时没见到用快速幂矩阵做这道题的程序,然后我自己写了一个)

#include<iostream>
#include<cstring>
#include<cstdio>
//#define	DEBUG
struct Matrix
{
	long long m[2][2];
	Matrix()
	{
		memset(m,0,sizeof(m));
	}
};

long long n,m;

Matrix mul(Matrix a,Matrix b,int m)
{
	Matrix res;
	for(long long i=0;i<2;++i)
		for(long long j=0;j<2;j++)
		{
			for(long long k=0;k<2;k++)
			{
				res.m[i][j]+=a.m[i][k]*b.m[k][j];
			}
			res.m[i][j]%=m;
		}
	return res;	
}

int main()
{
	Matrix x,a,res;
	
	
	a.m[0][0]=1;
	a.m[0][1]=0;
	a.m[1][0]=1;
	a.m[1][1]=2;
	
	while(scanf("%lld%lld",&n,&m)!=EOF)
	{
		x.m[0][0]=1;
		x.m[0][1]=0;
		x.m[1][0]=2;
		x.m[1][1]=4;
		
		res.m[0][0]=1;
		res.m[0][1]=0;
		res.m[1][0]=0;
		res.m[1][1]=1;
		if(n&1)
		{
			n=(n-1)/2;
			while(n)
			{
				if(n&1) res=mul(x,res,m);
				x=mul(x,x,m);
				n>>=1;	
			}
			res=mul(a,res,m);
#ifdef	DEBUG
			for(long long i=0;i<2;++i)
			{
				for(long long j=0;j<2;++j)
					std::cout<<res.m[i][j]<<' ';
				std::cout<<std::endl;
			}	
#endif				
		}else
		{
			n=n/2;
			while(n)
			{
				if(n&1) res=mul(x,res,m);
				x=mul(x,x,m);
				n>>=1;	
			}	
#ifdef	DEBUG
			for(long long i=0;i<2;++i)
			{
				for(long long j=0;j<2;++j)
					std::cout<<res.m[i][j]<<' ';
				std::cout<<std::endl;
			}	
#endif		
		}
		
		std ::cout<<res.m[1][0]<<std::endl; 
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Little_Small_Joze/article/details/79463804