标签:== ace 溢出 ios 链接 mes main print cas
题目:Algebraic Problem
链接:https://vjudge.net/problem/LightOJ-1070
分析:
1)$ a^n+b^n = ( a^{n-1}+b^{n-1} )*(a+b) - (a*b^{n-1}+a^{n-1}*b) $
构造矩阵: $ \left[ \begin{array}{cc} 0 & -1 \\ a*b & a+b \end{array} \right] $
$$ \left[ \begin{array}{cc} a*b^{n-1}+a^{n-1}*b & a^{n-1}+b^{n-1} \end{array} \right] * \left[ \begin{array}{cc} 0 & -1 \\ a*b & a+b \end{array} \right] = \left[ \begin{array}{cc} a*b^n+a^n*b & a^n+b^n \end{array} \right] $$
2)注意特判0的情况,至于对$2^{64}$取模,开unsigned long long,自然溢出即可。
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 typedef unsigned long long LLU; 5 typedef unsigned int uint; 6 struct Matrix{ 7 LLU a[2][2]; 8 Matrix(int f=0){ 9 memset(a,0,sizeof a); 10 if(f==1)for(int i=0;i<2;++i)a[i][i]=1; 11 } 12 }; 13 Matrix operator*(Matrix& A,Matrix& B){ 14 Matrix C; 15 for(int k=0;k<2;++k) 16 for(int i=0;i<2;++i) 17 for(int j=0;j<2;++j) 18 C.a[i][j]+=A.a[i][k]*B.a[k][j]; 19 return C; 20 } 21 Matrix operator^(Matrix A,uint n){ 22 Matrix Rt(1); 23 for(;n;n>>=1){ 24 if(n&1)Rt=Rt*A; 25 A=A*A; 26 } 27 return Rt; 28 } 29 int main(){ 30 int T;scanf("%d",&T); 31 Matrix A,ANS;LLU p,q;uint n; 32 for(int i=1;i<=T;++i){ 33 scanf("%llu%llu%u",&p,&q,&n); 34 if(n==0){ 35 printf("Case %d: 2\n",i); 36 continue; 37 } 38 A.a[0][0]=0;A.a[0][1]=-1; 39 A.a[1][0]=q;A.a[1][1]=p; 40 ANS=A^(n-1); 41 LLU ans=2*q*ANS.a[0][1]+ANS.a[1][1]*p; 42 printf("Case %d: %llu\n",i,ans); 43 } 44 return 0; 45 } 46
3)$ a^n + b^n = (a^{n-1}+b^{n-1})*(a+b) - (a*b^{n-1}+a^{n-1}*b) = (a^{n-1}+b^{n-1})*(a+b)-a*b*(b^{n-2}+a^{n-2}) $
构造矩阵:$ \left[ \begin{array}{cc} a+b & -ab \\ 1 & 0 \end{array} \right] $
$$ \left[ \begin{array}{cc} a+b & -ab \\ 1 & 0 \end{array} \right] * \left[ \begin{array}{c} a^{n-1}+b^{n-1} \\ a^{n-2}+b^{n-2} \end{array} \right] = \left[ \begin{array}{c} a^n+b^n \\ a^{n-1}+b^{n-1} \end{array} \right] $$
[LightOJ1070]Algebraic Problem
标签:== ace 溢出 ios 链接 mes main print cas
原文地址:https://www.cnblogs.com/hjj1871984569/p/10034169.html