1126 求递推序列的第N项(矩阵快速幂)

思路:很普通的矩阵快速幂,直接构造就可以了。但是这题贼坑,他所谓的取膜和我们平时说的不一样,负数取膜要变成正的,浪费了我2个多小时一直以为是模板问题。总之垃圾题一道。

 1 #include <iostream>
 2 #include <queue>
 3 #include <stack>
 4 #include <cstdio>
 5 #include <vector>
 6 #include <map>
 7 #include <set>
 8 #include <bitset>
 9 #include <algorithm>
10 #include <cmath>
11 #include <cstring>
12 #include <cstdlib>
13 #include <string>
14 #include <sstream>
15 #include <time.h>
16 #define x first
17 #define y second
18 #define pb push_back
19 #define mp make_pair
20 #define lson l,m,rt*2
21 #define rson m+1,r,rt*2+1
22 #define mt(A,B) memset(A,B,sizeof(A))
23 #define mod 7
24 using namespace std;
25 typedef long long LL;
26 const double PI = acos(-1);
27 const int N=2;
28 const int inf = 0x3f3f3f3f;
29 const LL INF=0x3f3f3f3f3f3f3f3fLL;
30 LL one,two,three;
31 struct Mat
32 {
33     LL mat[N][N];
34 };
35 Mat operator *(Mat a,Mat b)
36 {
37     Mat c;
38     memset(c.mat,0,sizeof(c.mat));
39     int i,j,k;
40     for(i=0; i<N; i++)
41     {
42         for(j=0; j<N; j++)
43         {
44             for(k=0; k<N; k++)
45             {
46                 c.mat[i][j]=(c.mat[i][j]+a.mat[i][k]*b.mat[k][j])%7;
47             }
48         }
49     }
50     return c;
51 }
52 Mat powermod(Mat a,int n)
53 {
54     Mat ans={1,0,1,0};//初始矩阵
55     int i,j;
56     if(n<0)return ans;
57     while(n)
58     {
59         if(n&1)
60         {
61             ans=ans*a;//矩阵a是我们所要构造的矩阵即a^n。
62         }
63         a=a*a;
64         n/=2;
65     }
66     return ans;
67 }
68 int main()
69 {
70 #ifdef Local
71     freopen("data.txt","r",stdin);
72 #endif
73     int n;
74     LL o;
75     cin>>one>>two>>n;
76     Mat p={0,(two%mod+mod)%mod,1,(one%mod+mod)%mod},q;
77     q=powermod(p,n-2);
78     cout<<q.mat[0][1]<<endl;
79 #ifdef Local
80     cerr << "time: " << (LL) clock() * 1000 / CLOCKS_PER_SEC << " ms" << endl;
81 #endif
82 }
View Code
原文地址:https://www.cnblogs.com/27sx/p/6297186.html