首页 > 代码库 > HDU 4686 Arc of Dream 矩阵快速幂

HDU 4686 Arc of Dream 矩阵快速幂

题意:给你两个线形方程求他们前n项相乘的和

解题思路:第一次知道了怎么去构造需要由自己本身元素组成的中间矩阵的方法详细题解看这里

http://blog.csdn.net/chenguolinblog/article/details/10341625

不过这题跑到了 1300 + , 正确解法应该是数论什么的吧。

解题代码:

  1 // File Name: temp.cpp  2 // Author: darkdream  3 // Created Time: 2014年09月17日 星期三 11时35分45秒  4   5 #include<vector>  6 #include<list>  7 #include<map>  8 #include<set>  9 #include<deque> 10 #include<stack> 11 #include<bitset> 12 #include<algorithm> 13 #include<functional> 14 #include<numeric> 15 #include<utility> 16 #include<sstream> 17 #include<iostream> 18 #include<iomanip> 19 #include<cstdio> 20 #include<cmath> 21 #include<cstdlib> 22 #include<cstring> 23 #include<ctime> 24 #define LL long long 25 #define m 1000000007 26 using namespace std; 27 LL  n , d,k;  28 LL  a0 ,ax,ay; 29 LL  b0 ,bx,by; 30 struct Matrix 31 { 32    LL   mat[15][15]; 33    void clear() 34    { 35       memset(mat,0,sizeof(mat)); 36    } 37    void output() 38    { 39      for(int i = 0  ;i < n ;i ++) 40      { 41        for(int j = 0 ;j < n ;j ++) 42            printf("%I64d ",mat[i][j]); 43      printf("\n"); 44      } 45    } 46    void init() 47    { 48       clear(); 49       mat[0][0] = ax*bx %m ;  50       mat[0][1] = ax*by %m ;  51       mat[0][2] = bx*ay %m ; 52       mat[0][3] = 1; 53       mat[1][1] = ax%m; 54       mat[1][4] = 1;; 55       mat[2][2] = bx%m;  56       mat[2][5] = 1; 57       mat[3][3] = 1; 58       mat[4][4] = 1; 59       mat[5][5] = 1; 60       mat[6][0] = 1; 61       mat[6][6] = 1;  62       n = 7 ; 63    } 64    Matrix operator *(const Matrix &b) const 65    { 66        Matrix ret; 67        ret.clear(); 68        for(int i = 0 ;i < n ;i ++) 69            for(int j = 0;j < n;j ++) 70            { 71                for(int s = 0 ;s < n ;s ++) 72                { 73                  ret.mat[i][j] =(ret.mat[i][j] + mat[i][s] * b.mat[s][j] %m ) %m  ; // 第I 行  第J  列         74                } 75            } 76        return ret; 77    } 78 }; 79 Matrix Pow( Matrix a ,LL t ) 80 { 81   Matrix ret; 82   ret.clear(); 83   for(int i = 0 ;i < n ;i ++) 84        ret.mat[i][i] = 1; 85   Matrix tmp = a;  86   while(t) 87   { 88       if(t&1) ret = ret * tmp; 89       tmp = tmp * tmp; 90       t >>=1; 91   } 92   return ret; 93 } 94 int main(){ 95  96     while(scanf("%I64d",&k) != EOF) 97     { 98        scanf("%I64d %I64d %I64d",&a0,&ax,&ay); 99        scanf("%I64d %I64d %I64d",&b0,&bx,&by);100        Matrix a;101        a.init();102        if(k == 0 )103        {  printf("0\n");104           continue;105        }106        a = Pow(a,k);107        //a.output();108        LL ans = 0 ; 109        ans = ((((((a.mat[6][0]* (a0*b0 %m )+ a.mat[6][1] * a0) % m + a.mat[6][2]* b0) %m + a.mat[6][3] * (ay*by % m))%m + a.mat[6][4] * ay)%m + a.mat[6][5]*by)%m )%m ;110        printf("%I64d\n",ans);111     }112     return 0;113 }
View Code

 

HDU 4686 Arc of Dream 矩阵快速幂