hdu-4990 Reading comprehension

题意:

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

给出n,m

思路:

看见别的题解忍不住想吐槽一下

这个题目没有那么复杂

   if(i&1)ans=(ans*2+1)%m; 
      else ans=ans*2%m; 

i从1开始,必定一奇一偶,如果为奇数再多一次ans=(ans*2+1)%m

所以把   ans=2*((ans*2+1)%m)%m看成一次变化

 ans=(4*ans+1)%m

如果n为奇数再ans=(ans*2+1)%m

#include<bits/stdc++.h>

using namespace std;
long long N;
struct node
{
	long long a[2][2];
};
const node A={
	          { 4,0
	           ,1,1
			  }
             };
const node B={
	          {0,2
	          ,0,0
	          }
             };
node cheng(node a,node b)
{
	node c;
	memset(c.a,0,sizeof(c.a));
	for(int i=0;i<2;i++){
	for(int j=0;j<2;j++)
	for(int k=0;k<2;k++)
	c.a[i][j]=(c.a[i][j]+(a.a[i][k]*b.a[k][j])%N)%N;
	}
	return c;
}

int main()
{
	int n,k;
	node a,b;
	while(~scanf("%d%lld",&n,&N))
    {
    	a=A;
    	b=B;
    	k=n;
    	n>>=1;
    	while(n)
    	{
    		if(n&1) b=cheng(b,a);
    		n>>=1;
    		a=cheng(a,a);
    	}
    	if(k&1) b.a[0][0]=(2*b.a[0][0]+1)%N;
    	printf("%lld\n",(b.a[0][0]%N+N)%N);
    }	
	return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值