给你下面程序:
#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
",ans);
}
return 0;
}
【数据范围】
【分析】
通过打表得知,因为n太大肯定不能暴力做,开始想着通过这个公式等比数列求和就可以做,但是后面发现因为要,而m的值不是定值,求逆元就不一定有。所以构造矩阵来做:
由此可转移如下:
【代码】
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long LL;
typedef vector<LL> vec;
typedef vector<vec> mat;
void Init(mat &A) {//构造矩阵
A[0][0] = 0; A[0][1] = 1LL, A[0][2] = 1LL;
A[1][0] = 1LL; A[1][1] = 0, A[1][2] = 0;
A[2][0] = 0; A[2][1] = 0, A[2][2] = 2LL;
}
mat mul(mat &A, mat &B, LL m) {//矩阵乘法
mat C(A.size(), vec(B[0].size()));
for(int i = 0; i < A.size(); i++)
for(int k = 0; k < B.size(); k++)
for(int j = 0; j < B[0].size(); j++)
C[i][j] = (C[i][j] + A[i][k] * B[k][j] % m) % m;
return C;
}
mat pow(mat &A, LL n, LL m) {//矩阵快速幂
mat B(A.size(), vec(A.size()));
for(int i = 0; i < A.size(); i++)B[i][i] = 1LL;
while(n > 0) {
if(n & 1)B = mul(B, A, m);
n >>= 1;
A = mul(A, A, m);
}
return B;
}
void solve(mat A, LL n, LL m) {
LL res = 0;
if(n <= 2LL)res = n % m;
else {
A = pow(A, n - 2LL, m);
res = (A[0][0] * 2LL + A[0][1] + A[0][2] * 4LL % m) % m;
}
printf("%lld
", res);
}
int main() {
LL n, m;
while(~scanf("%lld%lld", &n, &m)) {
mat A(3, vec(3));
Init(A);
solve(A, n, m);
}
return 0;
}