# HDU 4990 Reading comprehension（找规律+矩阵快速幂）

Problem Description
Read the program below carefully then answer the question.
#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```

Sample Output
```1
5```

Source

```#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define LL __int64
struct Matrix
{
LL  m[5][5];
} I,A,B,T;

LL a,b,n, mod;
int ssize = 3;

Matrix Mul(Matrix a,Matrix b)
{
int i,j,k;
Matrix c;
for (i = 1; i <= ssize; i++)
{
for(j = 1; j <= ssize; j++)
{
c.m[i][j]=0;
for(k = 1; k <= ssize; k++)
{
c.m[i][j]+=(a.m[i][k]*b.m[k][j]);
c.m[i][j]%=mod;
}
}
}
return c;
}

Matrix quickpagow(int n)
{
Matrix m=A, b=I;
while(n)
{
if(n&1)
b=Mul(b,m);
n=n>>1;
m=Mul(m,m);
}
return b;
}

int main()
{
while(~scanf("%I64d%I64d",&n,&mod))
{
memset(I.m,0,sizeof(I.m));
memset(A.m,0,sizeof(A.m));
memset(B.m,0,sizeof(B.m));
for(int i = 1; i <= ssize; i++)
{
I.m[i][i]=1;
}
B.m[1][1] = 1, B.m[1][2] = 2, B.m[1][3] = 1;
A.m[1][2] = 2;
A.m[2][1]=A.m[2][2]=A.m[3][2]=A.m[3][3]=1;
if(n==1)
{
printf("%I64d\n",1%mod);
continue;
}
if(n==2)
{
printf("%I64d\n",2%mod);
continue;
}
T = quickpagow(n-2);
T = Mul(B,T);
printf("%I64d\n",T.m[1][2]%mod);
}
return 0;
}
```

HDU 4990 Reading comprehension（找规律+矩阵快速幂）

(0)
(0)

0条

© 2014 mamicode.com 版权所有 京ICP备13008772号-2