Reading comprehension+矩阵快速幂

Reading comprehension

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3010    Accepted Submission(s): 1182

 

Problem Description

Read the program below carefully then answer the question.
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include
#include
#include
#include
#include
#include

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

Source

BestCoder Round #8

AC代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
ll n,mod;
struct test
{
    ll numbers[3][3];
    test()
    {
        numbers[0][0] = 1, numbers[0][1] = 2, numbers[0][2] = 1;
        numbers[1][0] = 1, numbers[1][1] = 0, numbers[1][2] = 0;
        numbers[2][0] = 0, numbers[2][1] = 0, numbers[2][2] = 1;
    }
};
test multiplying(test &AA,test &BB)
{
   test r;
   for(int i=0;i<3;i++)
   {
      for(int j=0;j<3;j++)
      {
         r.numbers[i][j]=0;
         for(int k=0;k<3;k++)
         {
             r.numbers[i][j]=(r.numbers[i][j]+(AA.numbers[i][k]*BB.numbers[k][j])%mod)%mod;
         } 
      }
   }
   return r;
}
void Pow(test A,ll n)
{
    test B;
    B.numbers[0][0]=2;
    B.numbers[1][0]=1;
    B.numbers[2][0]=1;
    while(n>0)
    {
       if(n&1)B=multiplying(A,B);
       A=multiplying(A,A); 
       n=n>>1;
    }
    cout << B.numbers[0][0]%mod << endl;
}
int main()
{
    while(cin >> n >> mod)
    {
        if(n==1)
        {
          cout << 1%mod << endl; //和队友找了半天才发现,此处有坑!
           continue ;
        }
        test A;
        Pow(A,n-2);
    }
} 

细节决定成败!!!

你可能感兴趣的:(C/C++,HDU)