九度 oj 题目1081:递推数列

来源:互联网 发布:java图的深度优先遍历 编辑:程序博客网 时间:2024/04/29 17:27


http://ac.jobdu.com/problem.php?pid=1081


参考了(照抄了)http://blog.csdn.net/zxasqwedc/article/details/8763967 


#include <stdio.h>#include <cstdlib>#include <cstring>#define LL long longstatic LL a0,a1,p,q,k; typedef struct matrix{     LL a[2][2]; } Matrix; Matrix multiply(Matrix m1, Matrix m2){     Matrix ret ;    ret.a[0][0] = ret.a[0][1] = ret.a[1][0] = ret.a[1][1] = 0;    for (int i = 0; i < 2; ++i) {         for (int j = 0; j < 2; ++j) {             for (int t = 0; t < 2; ++t) {                 ret.a[i][j] += (m1.a[i][t] * m2.a[t][j])%10000;             }          }      }      return ret;}  Matrix matrixPow(Matrix mat, LL n){     Matrix ret;    ret.a[0][0] = 1,ret.a[1][0] = 0,ret.a[0][1]=0,ret.a[1][1] = 1;    if(n == 0)  return ret;     else if( n==1 ) return mat;     else{         if(n&1){             ret =  matrixPow(mat,n/2);              ret = multiply(ret, ret);             ret = multiply(mat,ret);             return ret;        }else{             ret = matrixPow(mat,n/2);              ret = multiply(ret,ret);             return ret;        }        } }  int main(){     while(scanf("%lld %lld %lld %lld %lld",&a0,&a1,&p,&q,&k)!=EOF){         if(k==0) printf("%lld\n" ,a0);          else if(k==1) printf("%lld\n" ,a1);          else{             Matrix m;            m.a[0][0] = 0,m.a[0][1] = 1,m.a[1][0] = q,m.a[1][1] = p;            Matrix ret = matrixPow(m,k-1);            printf("%lld\n",(ret.a[1][0]*a0+ret.a[1][1]*a1)%10000 );         }     }  } 


0 0
原创粉丝点击