快速幂1005

来源:互联网 发布:网络组织 企业家才能 编辑:程序博客网 时间:2024/06/03 13:01

Reading comprehension

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 12   Accepted Submission(s) : 4

Font: Times New Roman | Verdana | Georgia

Font Size:  

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 103 100

Sample Output

15
思路:这题其实可以发现规律,f[n]=2*f[n-2]+f[n-1]+1,这样就可以用矩阵快速幂了,一开始把数组定义为int,一直wa,后来用在结构体里面来定义long long int的数组就过了。
代码:
#include <iostream>#include <stdio.h>#include <string.h>#include <algorithm>#include <queue>#include <cmath>using namespace std;long long int L;long long int M;struct node{    long long int a[5][5];}a,b,c;node poww(node m,node n){    int i,j;  node d;    for(i=0;i<4;i++)    {        for(j=0;j<4;j++)        {            d.a[i][j]=0;            for(int k=0;k<4;k++)                d.a[i][j]=(d.a[i][j]+m.a[i][k]*n.a[k][j])%M;        }    }    return d;}node powww(node m,node n){    int i,j;   node d;    for(i=0;i<4;i++)    {        d.a[i][0]=0;        for(j=0;j<4;j++)        {            d.a[i][0]=(d.a[i][0]+n.a[i][j]*m.a[j][0])%M;        }    }   return d;}int zz(long  long int k){    int i,j;    for(i=0;i<3;i++)        for(j=0;j<3;j++)        b.a[i][j]=0;     b.a[0][0]=b.a[0][2]=1;    b.a[0][1]=2;    b.a[1][0]=b.a[2][2]=1;    for(i=0;i<4;i++)        c.a[i][0]=a.a[i][0];    while(k)    {        if(k&1)c=powww(c,b);        b=poww(b,b);        k>>=1;    }    return c.a[0][0];}int main(){    a.a[0][0]=5;    a.a[1][0]=2;    a.a[2][0]=1;    while(scanf("%lld %lld",&L,&M)!=EOF)    {        if(L<=3)        {            int i;            for(i=0;i<4-L;i++)            {                if(i==3-L)                {                    cout<<a.a[i][0]%M<<endl;                    break;                }            }        }        else        {            cout<<zz(L-3)<<endl;        }    }    return 0;}

原创粉丝点击