题意:读程序,找规律
思路:我们把程序输出发现序列为1,2,5,10,21,42,85,170,递推式f(n)=2*f(n-2)+f(n-1)+1
代码:
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #define ll long long using namespace std; const int N=3,M=3,P=3; ll mod; struct Matrix { ll m[N][N]; }; Matrix A={1,2,1, 1,0,0, 0,0,1}; Matrix I={1,0,0, 0,1,0, 0,0,1}; Matrix multi(Matrix a,Matrix b) { Matrix ans; for(int i=0;i<N;i++) { for(int j=0;j<M;j++) { ans.m[i][j]=0; for(int k=0;k<P;k++) { ans.m[i][j]+=(a.m[i][k]*b.m[k][j])%mod; } ans.m[i][j]%=mod; } } return ans; } Matrix power(Matrix a,ll b) { Matrix ans=I; while(b) { if(b&1) { ans=multi(ans,a); } b=b/2; a=multi(a,a); } return ans; } int main() { ll n; while(cin>>n>>mod) { if(n==1) { cout<<(1)%mod<<endl;continue; } else if(n==2) { cout<<(2)%mod<<endl; continue; } Matrix ans=power(A,n-2); cout<<(ans.m[0][0]*2+ans.m[0][1]*1+ans.m[0][2])%mod<<endl; } return 0; }