您的位置:首页 > 其它

Reading comprehension HDU - 4990(矩阵快速幂 递推)

2018-02-13 11:14 435 查看
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
4000
\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


题意:当n为奇数时,f
= 2*f[n-1]+1,f[n-1] = 2*f[n-2],所以:f
= f[n-1] + 2*f[n-2] + 1;

当n为偶数时,f
= 2*f[n-1],f[n-1] = 2*f[n-2] + 1,所以:f
= f[n-1] + 2*f[n-2] + 1;

综上:f
= f[n-1] + 2*f[n-2] + 1,构造矩阵:



利用矩阵快速幂求f(n)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
typedef long long LL;
LL MOD;
const int Size = 3;
struct MA
{
LL mat[Size][Size];
};

MA mul(MA x, MA y)
{
MA ret;
memset(ret.mat, 0, sizeof(ret.mat));
for(int i = 0; i<Size; i++)
for(int j = 0; j<Size; j++)
for(int k = 0; k<Size; k++)
{
ret.mat[i][j] += (1LL*x.mat[i][k]*y.mat[k][j])%MOD;
ret.mat[i][j] %= MOD;
}
return ret;
}

MA qpow(MA x, LL y)
{
MA s;
memset(s.mat,0,sizeof(s.mat));
for(int i=0;i<Size;i++) s.mat[i][i] = 1;
while(y)
{
if(y&1) s = mul(s, x);
x = mul(x, x);
y >>= 1;
}
return s;
}

MA tmp = {
1, 2, 1,
1, 0, 0,
0, 0, 1
};

int main()
{
LL n, m;
while(~scanf("%lld%lld",&n,&m))
{
MOD = m;
if(n<=2)
{
printf("%lld\n", n%MOD);
continue;
}

MA s = tmp;
s = qpow(s, n-2);
LL ans = ((2LL*s.mat[0][0]%MOD + s.mat[0][1])%MOD+s.mat[0][2])%MOD;
printf("%lld\n", ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: