标签:
题意:已知x+y=A x*y=B 求X^n+Y^n.
思路:设f(i)为X^n+Y^n 则f(n)=A*f(n-1)-B*f(n-2) 然后矩阵快速幂.
在矩阵乘法过程中有负数 在取余之前要先加上MOD.
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> #include <string> #include <map> using namespace std; typedef long long ll; const int INF=0x3f3f3f3f; const ll MOD=1e9+7; const int MAXN=2; struct Matrix{ ll m[MAXN][MAXN]; Matrix() { memset(m,0,sizeof(m)); } }; Matrix mtMul(Matrix A, Matrix B) { int i,j,k; Matrix C; for(i = 0; i <MAXN; i ++) for(j = 0; j <MAXN; j ++) for(k = 0; k <MAXN; k ++) C.m[i][j]=(C.m[i][j]%MOD+((A.m[i][k]%MOD)*((B.m[k][j])%MOD))%MOD+MOD)%MOD; return C; } Matrix mtPow(Matrix A, ll k) { if(k == 1) return A; Matrix B = mtPow(A, k / 2); if(k % 2 == 0) return mtMul(B, B); else return mtMul(mtMul(B, B), A); } int main() { ll a,b,n; while(scanf("%lld%lld%lld",&a,&b,&n)!=EOF) { Matrix tmp; tmp.m[0][0]=a; tmp.m[0][1]=-b; tmp.m[1][0]=1; if(n==1) printf("%d\n",a); else { Matrix ans=mtPow(tmp,n-1); printf("%lld\n",(((ans.m[0][0]%MOD)*(a%MOD))%MOD+((ans.m[0][1]%MOD)*2)%MOD)%MOD); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/onlyAzha/p/4760946.html